2
0

gdscript_parser.cpp 147 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398
  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<Multiplayer::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. advance();
  1463. continue;
  1464. }
  1465. #ifdef DEBUG_ENABLED
  1466. if (have_wildcard_without_continue) {
  1467. push_warning(branch->patterns[0], GDScriptWarning::UNREACHABLE_PATTERN);
  1468. }
  1469. if (branch->has_wildcard) {
  1470. have_wildcard = true;
  1471. if (branch->block->has_return) {
  1472. wildcard_has_return = true;
  1473. }
  1474. if (!branch->block->has_continue) {
  1475. have_wildcard_without_continue = true;
  1476. }
  1477. }
  1478. if (!branch->block->has_return) {
  1479. all_have_return = false;
  1480. }
  1481. #endif
  1482. match->branches.push_back(branch);
  1483. }
  1484. consume(GDScriptTokenizer::Token::DEDENT, R"(Expected an indented block after "match" statement.)");
  1485. #ifdef DEBUG_ENABLED
  1486. if (wildcard_has_return || (all_have_return && have_wildcard)) {
  1487. current_suite->has_return = true;
  1488. }
  1489. #endif
  1490. return match;
  1491. }
  1492. GDScriptParser::MatchBranchNode *GDScriptParser::parse_match_branch() {
  1493. MatchBranchNode *branch = alloc_node<MatchBranchNode>();
  1494. bool has_bind = false;
  1495. do {
  1496. PatternNode *pattern = parse_match_pattern();
  1497. if (pattern == nullptr) {
  1498. continue;
  1499. }
  1500. if (pattern->pattern_type == PatternNode::PT_BIND) {
  1501. has_bind = true;
  1502. }
  1503. if (branch->patterns.size() > 0 && has_bind) {
  1504. push_error(R"(Cannot use a variable bind with multiple patterns.)");
  1505. }
  1506. if (pattern->pattern_type == PatternNode::PT_REST) {
  1507. push_error(R"(Rest pattern can only be used inside array and dictionary patterns.)");
  1508. } else if (pattern->pattern_type == PatternNode::PT_BIND || pattern->pattern_type == PatternNode::PT_WILDCARD) {
  1509. branch->has_wildcard = true;
  1510. }
  1511. branch->patterns.push_back(pattern);
  1512. } while (match(GDScriptTokenizer::Token::COMMA));
  1513. if (branch->patterns.is_empty()) {
  1514. push_error(R"(No pattern found for "match" branch.)");
  1515. }
  1516. if (!consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" patterns.)")) {
  1517. return nullptr;
  1518. }
  1519. // Save continue state.
  1520. bool could_continue = can_continue;
  1521. bool was_continue_match = is_continue_match;
  1522. // Allow continue for match.
  1523. can_continue = true;
  1524. is_continue_match = true;
  1525. SuiteNode *suite = alloc_node<SuiteNode>();
  1526. if (branch->patterns.size() > 0) {
  1527. List<StringName> binds;
  1528. branch->patterns[0]->binds.get_key_list(&binds);
  1529. for (const StringName &E : binds) {
  1530. SuiteNode::Local local(branch->patterns[0]->binds[E], current_function);
  1531. suite->add_local(local);
  1532. }
  1533. }
  1534. branch->block = parse_suite("match pattern block", suite);
  1535. // Restore continue state.
  1536. can_continue = could_continue;
  1537. is_continue_match = was_continue_match;
  1538. return branch;
  1539. }
  1540. GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_root_pattern) {
  1541. PatternNode *pattern = alloc_node<PatternNode>();
  1542. switch (current.type) {
  1543. case GDScriptTokenizer::Token::VAR: {
  1544. // Bind.
  1545. advance();
  1546. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected bind name after "var".)")) {
  1547. return nullptr;
  1548. }
  1549. pattern->pattern_type = PatternNode::PT_BIND;
  1550. pattern->bind = parse_identifier();
  1551. PatternNode *root_pattern = p_root_pattern == nullptr ? pattern : p_root_pattern;
  1552. if (p_root_pattern != nullptr) {
  1553. if (p_root_pattern->has_bind(pattern->bind->name)) {
  1554. push_error(vformat(R"(Bind variable name "%s" was already used in this pattern.)", pattern->bind->name));
  1555. return nullptr;
  1556. }
  1557. }
  1558. if (current_suite->has_local(pattern->bind->name)) {
  1559. 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));
  1560. return nullptr;
  1561. }
  1562. root_pattern->binds[pattern->bind->name] = pattern->bind;
  1563. } break;
  1564. case GDScriptTokenizer::Token::UNDERSCORE:
  1565. // Wildcard.
  1566. advance();
  1567. pattern->pattern_type = PatternNode::PT_WILDCARD;
  1568. break;
  1569. case GDScriptTokenizer::Token::PERIOD_PERIOD:
  1570. // Rest.
  1571. advance();
  1572. pattern->pattern_type = PatternNode::PT_REST;
  1573. break;
  1574. case GDScriptTokenizer::Token::BRACKET_OPEN: {
  1575. // Array.
  1576. advance();
  1577. pattern->pattern_type = PatternNode::PT_ARRAY;
  1578. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  1579. do {
  1580. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  1581. if (sub_pattern == nullptr) {
  1582. continue;
  1583. }
  1584. if (pattern->rest_used) {
  1585. push_error(R"(The ".." pattern must be the last element in the pattern array.)");
  1586. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  1587. pattern->rest_used = true;
  1588. }
  1589. pattern->array.push_back(sub_pattern);
  1590. } while (match(GDScriptTokenizer::Token::COMMA));
  1591. }
  1592. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" to close the array pattern.)");
  1593. break;
  1594. }
  1595. case GDScriptTokenizer::Token::BRACE_OPEN: {
  1596. // Dictionary.
  1597. advance();
  1598. pattern->pattern_type = PatternNode::PT_DICTIONARY;
  1599. do {
  1600. if (check(GDScriptTokenizer::Token::BRACE_CLOSE) || is_at_end()) {
  1601. break;
  1602. }
  1603. if (match(GDScriptTokenizer::Token::PERIOD_PERIOD)) {
  1604. // Rest.
  1605. if (pattern->rest_used) {
  1606. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  1607. } else {
  1608. PatternNode *sub_pattern = alloc_node<PatternNode>();
  1609. sub_pattern->pattern_type = PatternNode::PT_REST;
  1610. pattern->dictionary.push_back({ nullptr, sub_pattern });
  1611. pattern->rest_used = true;
  1612. }
  1613. } else {
  1614. ExpressionNode *key = parse_expression(false);
  1615. if (key == nullptr) {
  1616. push_error(R"(Expected expression as key for dictionary pattern.)");
  1617. }
  1618. if (match(GDScriptTokenizer::Token::COLON)) {
  1619. // Value pattern.
  1620. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  1621. if (sub_pattern == nullptr) {
  1622. continue;
  1623. }
  1624. if (pattern->rest_used) {
  1625. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  1626. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  1627. push_error(R"(The ".." pattern cannot be used as a value.)");
  1628. } else {
  1629. pattern->dictionary.push_back({ key, sub_pattern });
  1630. }
  1631. } else {
  1632. // Key match only.
  1633. pattern->dictionary.push_back({ key, nullptr });
  1634. }
  1635. }
  1636. } while (match(GDScriptTokenizer::Token::COMMA));
  1637. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected "}" to close the dictionary pattern.)");
  1638. break;
  1639. }
  1640. default: {
  1641. // Expression.
  1642. ExpressionNode *expression = parse_expression(false);
  1643. if (expression == nullptr) {
  1644. push_error(R"(Expected expression for match pattern.)");
  1645. return nullptr;
  1646. } else {
  1647. if (expression->type == GDScriptParser::Node::LITERAL) {
  1648. pattern->pattern_type = PatternNode::PT_LITERAL;
  1649. } else {
  1650. pattern->pattern_type = PatternNode::PT_EXPRESSION;
  1651. }
  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. if (current_function) { // Might be null in a getter or setter.
  2086. current_function->is_coroutine = true;
  2087. }
  2088. return await;
  2089. }
  2090. GDScriptParser::ExpressionNode *GDScriptParser::parse_array(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2091. ArrayNode *array = alloc_node<ArrayNode>();
  2092. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2093. do {
  2094. if (check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2095. // Allow for trailing comma.
  2096. break;
  2097. }
  2098. ExpressionNode *element = parse_expression(false);
  2099. if (element == nullptr) {
  2100. push_error(R"(Expected expression as array element.)");
  2101. } else {
  2102. array->elements.push_back(element);
  2103. }
  2104. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2105. }
  2106. pop_multiline();
  2107. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after array elements.)");
  2108. return array;
  2109. }
  2110. GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2111. DictionaryNode *dictionary = alloc_node<DictionaryNode>();
  2112. bool decided_style = false;
  2113. if (!check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2114. do {
  2115. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2116. // Allow for trailing comma.
  2117. break;
  2118. }
  2119. // Key.
  2120. ExpressionNode *key = parse_expression(false, true); // Stop on "=" so we can check for Lua table style.
  2121. if (key == nullptr) {
  2122. push_error(R"(Expected expression as dictionary key.)");
  2123. }
  2124. if (!decided_style) {
  2125. switch (current.type) {
  2126. case GDScriptTokenizer::Token::COLON:
  2127. dictionary->style = DictionaryNode::PYTHON_DICT;
  2128. break;
  2129. case GDScriptTokenizer::Token::EQUAL:
  2130. dictionary->style = DictionaryNode::LUA_TABLE;
  2131. break;
  2132. default:
  2133. push_error(R"(Expected ":" or "=" after dictionary key.)");
  2134. break;
  2135. }
  2136. decided_style = true;
  2137. }
  2138. switch (dictionary->style) {
  2139. case DictionaryNode::LUA_TABLE:
  2140. if (key != nullptr && key->type != Node::IDENTIFIER) {
  2141. push_error("Expected identifier as LUA-style dictionary key.");
  2142. advance();
  2143. break;
  2144. }
  2145. if (!match(GDScriptTokenizer::Token::EQUAL)) {
  2146. if (match(GDScriptTokenizer::Token::COLON)) {
  2147. push_error(R"(Expected "=" after dictionary key. Mixing dictionary styles is not allowed.)");
  2148. advance(); // Consume wrong separator anyway.
  2149. } else {
  2150. push_error(R"(Expected "=" after dictionary key.)");
  2151. }
  2152. }
  2153. if (key != nullptr) {
  2154. key->is_constant = true;
  2155. key->reduced_value = static_cast<IdentifierNode *>(key)->name;
  2156. }
  2157. break;
  2158. case DictionaryNode::PYTHON_DICT:
  2159. if (!match(GDScriptTokenizer::Token::COLON)) {
  2160. if (match(GDScriptTokenizer::Token::EQUAL)) {
  2161. push_error(R"(Expected ":" after dictionary key. Mixing dictionary styles is not allowed.)");
  2162. advance(); // Consume wrong separator anyway.
  2163. } else {
  2164. push_error(R"(Expected ":" after dictionary key.)");
  2165. }
  2166. }
  2167. break;
  2168. }
  2169. // Value.
  2170. ExpressionNode *value = parse_expression(false);
  2171. if (value == nullptr) {
  2172. push_error(R"(Expected expression as dictionary value.)");
  2173. }
  2174. if (key != nullptr && value != nullptr) {
  2175. dictionary->elements.push_back({ key, value });
  2176. }
  2177. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2178. }
  2179. pop_multiline();
  2180. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" after dictionary elements.)");
  2181. return dictionary;
  2182. }
  2183. GDScriptParser::ExpressionNode *GDScriptParser::parse_grouping(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2184. ExpressionNode *grouped = parse_expression(false);
  2185. pop_multiline();
  2186. if (grouped == nullptr) {
  2187. push_error(R"(Expected grouping expression.)");
  2188. } else {
  2189. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after grouping expression.)*");
  2190. }
  2191. return grouped;
  2192. }
  2193. GDScriptParser::ExpressionNode *GDScriptParser::parse_attribute(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2194. SubscriptNode *attribute = alloc_node<SubscriptNode>();
  2195. if (for_completion) {
  2196. bool is_builtin = false;
  2197. if (p_previous_operand && p_previous_operand->type == Node::IDENTIFIER) {
  2198. const IdentifierNode *id = static_cast<const IdentifierNode *>(p_previous_operand);
  2199. Variant::Type builtin_type = get_builtin_type(id->name);
  2200. if (builtin_type < Variant::VARIANT_MAX) {
  2201. make_completion_context(COMPLETION_BUILT_IN_TYPE_CONSTANT, builtin_type, true);
  2202. is_builtin = true;
  2203. }
  2204. }
  2205. if (!is_builtin) {
  2206. make_completion_context(COMPLETION_ATTRIBUTE, attribute, -1, true);
  2207. }
  2208. }
  2209. attribute->is_attribute = true;
  2210. attribute->base = p_previous_operand;
  2211. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier after "." for attribute access.)")) {
  2212. return attribute;
  2213. }
  2214. attribute->attribute = parse_identifier();
  2215. return attribute;
  2216. }
  2217. GDScriptParser::ExpressionNode *GDScriptParser::parse_subscript(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2218. SubscriptNode *subscript = alloc_node<SubscriptNode>();
  2219. make_completion_context(COMPLETION_SUBSCRIPT, subscript);
  2220. subscript->base = p_previous_operand;
  2221. subscript->index = parse_expression(false);
  2222. pop_multiline();
  2223. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" after subscription index.)");
  2224. return subscript;
  2225. }
  2226. GDScriptParser::ExpressionNode *GDScriptParser::parse_cast(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2227. CastNode *cast = alloc_node<CastNode>();
  2228. cast->operand = p_previous_operand;
  2229. cast->cast_type = parse_type();
  2230. if (cast->cast_type == nullptr) {
  2231. push_error(R"(Expected type specifier after "as".)");
  2232. return p_previous_operand;
  2233. }
  2234. return cast;
  2235. }
  2236. GDScriptParser::ExpressionNode *GDScriptParser::parse_call(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2237. CallNode *call = alloc_node<CallNode>();
  2238. if (previous.type == GDScriptTokenizer::Token::SUPER) {
  2239. // Super call.
  2240. call->is_super = true;
  2241. push_multiline(true);
  2242. if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  2243. // Implicit call to the parent method of the same name.
  2244. if (current_function == nullptr) {
  2245. push_error(R"(Cannot use implicit "super" call outside of a function.)");
  2246. pop_multiline();
  2247. return nullptr;
  2248. }
  2249. call->function_name = current_function->identifier->name;
  2250. } else {
  2251. consume(GDScriptTokenizer::Token::PERIOD, R"(Expected "." or "(" after "super".)");
  2252. make_completion_context(COMPLETION_SUPER_METHOD, call, true);
  2253. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after ".".)")) {
  2254. pop_multiline();
  2255. return nullptr;
  2256. }
  2257. IdentifierNode *identifier = parse_identifier();
  2258. call->callee = identifier;
  2259. call->function_name = identifier->name;
  2260. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after function name.)");
  2261. }
  2262. } else {
  2263. call->callee = p_previous_operand;
  2264. if (call->callee == nullptr) {
  2265. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2266. } else if (call->callee->type == Node::IDENTIFIER) {
  2267. call->function_name = static_cast<IdentifierNode *>(call->callee)->name;
  2268. make_completion_context(COMPLETION_METHOD, call->callee);
  2269. } else if (call->callee->type == Node::SUBSCRIPT) {
  2270. SubscriptNode *attribute = static_cast<SubscriptNode *>(call->callee);
  2271. if (attribute->is_attribute) {
  2272. if (attribute->attribute) {
  2273. call->function_name = attribute->attribute->name;
  2274. }
  2275. make_completion_context(COMPLETION_ATTRIBUTE_METHOD, call->callee);
  2276. } else {
  2277. // TODO: The analyzer can see if this is actually a Callable and give better error message.
  2278. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2279. }
  2280. } else {
  2281. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2282. }
  2283. }
  2284. // Arguments.
  2285. CompletionType ct = COMPLETION_CALL_ARGUMENTS;
  2286. if (call->function_name == "load") {
  2287. ct = COMPLETION_RESOURCE_PATH;
  2288. }
  2289. push_completion_call(call);
  2290. int argument_index = 0;
  2291. do {
  2292. make_completion_context(ct, call, argument_index++, true);
  2293. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  2294. // Allow for trailing comma.
  2295. break;
  2296. }
  2297. ExpressionNode *argument = parse_expression(false);
  2298. if (argument == nullptr) {
  2299. push_error(R"(Expected expression as the function argument.)");
  2300. } else {
  2301. call->arguments.push_back(argument);
  2302. }
  2303. ct = COMPLETION_CALL_ARGUMENTS;
  2304. } while (match(GDScriptTokenizer::Token::COMMA));
  2305. pop_completion_call();
  2306. pop_multiline();
  2307. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after call arguments.)*");
  2308. return call;
  2309. }
  2310. GDScriptParser::ExpressionNode *GDScriptParser::parse_get_node(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2311. if (match(GDScriptTokenizer::Token::LITERAL)) {
  2312. if (previous.literal.get_type() != Variant::STRING) {
  2313. push_error(R"(Expect node path as string or identifier after "$".)");
  2314. return nullptr;
  2315. }
  2316. GetNodeNode *get_node = alloc_node<GetNodeNode>();
  2317. make_completion_context(COMPLETION_GET_NODE, get_node);
  2318. get_node->string = parse_literal();
  2319. return get_node;
  2320. } else if (current.is_node_name()) {
  2321. GetNodeNode *get_node = alloc_node<GetNodeNode>();
  2322. int chain_position = 0;
  2323. do {
  2324. make_completion_context(COMPLETION_GET_NODE, get_node, chain_position++);
  2325. if (!current.is_node_name()) {
  2326. push_error(R"(Expect node path after "/".)");
  2327. return nullptr;
  2328. }
  2329. advance();
  2330. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  2331. identifier->name = previous.get_identifier();
  2332. get_node->chain.push_back(identifier);
  2333. } while (match(GDScriptTokenizer::Token::SLASH));
  2334. return get_node;
  2335. } else {
  2336. push_error(R"(Expect node path as string or identifier after "$".)");
  2337. return nullptr;
  2338. }
  2339. }
  2340. GDScriptParser::ExpressionNode *GDScriptParser::parse_preload(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2341. PreloadNode *preload = alloc_node<PreloadNode>();
  2342. preload->resolved_path = "<missing path>";
  2343. push_multiline(true);
  2344. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "preload".)");
  2345. make_completion_context(COMPLETION_RESOURCE_PATH, preload);
  2346. push_completion_call(preload);
  2347. preload->path = parse_expression(false);
  2348. if (preload->path == nullptr) {
  2349. push_error(R"(Expected resource path after "(".)");
  2350. }
  2351. pop_completion_call();
  2352. pop_multiline();
  2353. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after preload path.)*");
  2354. return preload;
  2355. }
  2356. GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2357. LambdaNode *lambda = alloc_node<LambdaNode>();
  2358. lambda->parent_function = current_function;
  2359. FunctionNode *function = alloc_node<FunctionNode>();
  2360. function->source_lambda = lambda;
  2361. function->is_static = current_function != nullptr ? current_function->is_static : false;
  2362. if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
  2363. function->identifier = parse_identifier();
  2364. }
  2365. bool multiline_context = multiline_stack.back()->get();
  2366. // Reset the multiline stack since we don't want the multiline mode one in the lambda body.
  2367. push_multiline(false);
  2368. if (multiline_context) {
  2369. tokenizer.push_expression_indented_block();
  2370. }
  2371. push_multiline(true); // For the parameters.
  2372. if (function->identifier) {
  2373. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after lambda name.)");
  2374. } else {
  2375. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after "func".)");
  2376. }
  2377. FunctionNode *previous_function = current_function;
  2378. current_function = function;
  2379. SuiteNode *body = alloc_node<SuiteNode>();
  2380. SuiteNode *previous_suite = current_suite;
  2381. current_suite = body;
  2382. parse_function_signature(function, body, "lambda");
  2383. current_suite = previous_suite;
  2384. bool previous_in_lambda = in_lambda;
  2385. in_lambda = true;
  2386. function->body = parse_suite("lambda declaration", body, true);
  2387. pop_multiline();
  2388. if (multiline_context) {
  2389. // If we're in multiline mode, we want to skip the spurious DEDENT and NEWLINE tokens.
  2390. while (check(GDScriptTokenizer::Token::DEDENT) || check(GDScriptTokenizer::Token::INDENT) || check(GDScriptTokenizer::Token::NEWLINE)) {
  2391. current = tokenizer.scan(); // Not advance() since we don't want to change the previous token.
  2392. }
  2393. tokenizer.pop_expression_indented_block();
  2394. }
  2395. current_function = previous_function;
  2396. in_lambda = previous_in_lambda;
  2397. lambda->function = function;
  2398. return lambda;
  2399. }
  2400. GDScriptParser::ExpressionNode *GDScriptParser::parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2401. // Just for better error messages.
  2402. GDScriptTokenizer::Token::Type invalid = previous.type;
  2403. switch (invalid) {
  2404. case GDScriptTokenizer::Token::QUESTION_MARK:
  2405. push_error(R"(Unexpected "?" in source. If you want a ternary operator, use "truthy_value if true_condition else falsy_value".)");
  2406. break;
  2407. default:
  2408. return nullptr; // Unreachable.
  2409. }
  2410. // Return the previous expression.
  2411. return p_previous_operand;
  2412. }
  2413. GDScriptParser::TypeNode *GDScriptParser::parse_type(bool p_allow_void) {
  2414. TypeNode *type = alloc_node<TypeNode>();
  2415. make_completion_context(p_allow_void ? COMPLETION_TYPE_NAME_OR_VOID : COMPLETION_TYPE_NAME, type);
  2416. if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
  2417. if (match(GDScriptTokenizer::Token::VOID)) {
  2418. if (p_allow_void) {
  2419. TypeNode *void_type = alloc_node<TypeNode>();
  2420. return void_type;
  2421. } else {
  2422. push_error(R"("void" is only allowed for a function return type.)");
  2423. }
  2424. }
  2425. // Leave error message to the caller who knows the context.
  2426. return nullptr;
  2427. }
  2428. IdentifierNode *type_element = parse_identifier();
  2429. type->type_chain.push_back(type_element);
  2430. if (match(GDScriptTokenizer::Token::BRACKET_OPEN)) {
  2431. // Typed collection (like Array[int]).
  2432. type->container_type = parse_type(false); // Don't allow void for array element type.
  2433. if (type->container_type == nullptr) {
  2434. push_error(R"(Expected type for collection after "[".)");
  2435. type = nullptr;
  2436. } else if (type->container_type->container_type != nullptr) {
  2437. push_error("Nested typed collections are not supported.");
  2438. }
  2439. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after collection type.)");
  2440. return type;
  2441. }
  2442. int chain_index = 1;
  2443. while (match(GDScriptTokenizer::Token::PERIOD)) {
  2444. make_completion_context(COMPLETION_TYPE_ATTRIBUTE, type, chain_index++);
  2445. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected inner type name after ".".)")) {
  2446. type_element = parse_identifier();
  2447. type->type_chain.push_back(type_element);
  2448. }
  2449. }
  2450. return type;
  2451. }
  2452. #ifdef TOOLS_ENABLED
  2453. static bool _in_codeblock(String p_line, bool p_already_in, int *r_block_begins = nullptr) {
  2454. int start_block = p_line.rfind("[codeblock]");
  2455. int end_block = p_line.rfind("[/codeblock]");
  2456. if (start_block != -1 && r_block_begins) {
  2457. *r_block_begins = start_block;
  2458. }
  2459. if (p_already_in) {
  2460. if (end_block == -1) {
  2461. return true;
  2462. } else if (start_block == -1) {
  2463. return false;
  2464. } else {
  2465. return start_block > end_block;
  2466. }
  2467. } else {
  2468. if (start_block == -1) {
  2469. return false;
  2470. } else if (end_block == -1) {
  2471. return true;
  2472. } else {
  2473. return start_block > end_block;
  2474. }
  2475. }
  2476. }
  2477. bool GDScriptParser::has_comment(int p_line) {
  2478. return tokenizer.get_comments().has(p_line);
  2479. }
  2480. String GDScriptParser::get_doc_comment(int p_line, bool p_single_line) {
  2481. const Map<int, GDScriptTokenizer::CommentData> &comments = tokenizer.get_comments();
  2482. ERR_FAIL_COND_V(!comments.has(p_line), String());
  2483. if (p_single_line) {
  2484. if (comments[p_line].comment.begins_with("##")) {
  2485. return comments[p_line].comment.trim_prefix("##").strip_edges();
  2486. }
  2487. return "";
  2488. }
  2489. String doc;
  2490. int line = p_line;
  2491. bool in_codeblock = false;
  2492. while (comments.has(line - 1)) {
  2493. if (!comments[line - 1].new_line || !comments[line - 1].comment.begins_with("##")) {
  2494. break;
  2495. }
  2496. line--;
  2497. }
  2498. int codeblock_begins = 0;
  2499. while (comments.has(line)) {
  2500. if (!comments[line].new_line || !comments[line].comment.begins_with("##")) {
  2501. break;
  2502. }
  2503. String doc_line = comments[line].comment.trim_prefix("##");
  2504. in_codeblock = _in_codeblock(doc_line, in_codeblock, &codeblock_begins);
  2505. if (in_codeblock) {
  2506. int i = 0;
  2507. for (; i < codeblock_begins; i++) {
  2508. if (doc_line[i] != ' ') {
  2509. break;
  2510. }
  2511. }
  2512. doc_line = doc_line.substr(i);
  2513. } else {
  2514. doc_line = doc_line.strip_edges();
  2515. }
  2516. String line_join = (in_codeblock) ? "\n" : " ";
  2517. doc = (doc.is_empty()) ? doc_line : doc + line_join + doc_line;
  2518. line++;
  2519. }
  2520. return doc;
  2521. }
  2522. 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) {
  2523. const Map<int, GDScriptTokenizer::CommentData> &comments = tokenizer.get_comments();
  2524. if (!comments.has(p_line)) {
  2525. return;
  2526. }
  2527. ERR_FAIL_COND(p_brief != "" || p_desc != "" || p_tutorials.size() != 0);
  2528. int line = p_line;
  2529. bool in_codeblock = false;
  2530. enum Mode {
  2531. BRIEF,
  2532. DESC,
  2533. TUTORIALS,
  2534. DONE,
  2535. };
  2536. Mode mode = BRIEF;
  2537. if (p_inner_class) {
  2538. while (comments.has(line - 1)) {
  2539. if (!comments[line - 1].new_line || !comments[line - 1].comment.begins_with("##")) {
  2540. break;
  2541. }
  2542. line--;
  2543. }
  2544. }
  2545. int codeblock_begins = 0;
  2546. while (comments.has(line)) {
  2547. if (!comments[line].new_line || !comments[line].comment.begins_with("##")) {
  2548. break;
  2549. }
  2550. String title, link; // For tutorials.
  2551. String doc_line = comments[line++].comment.trim_prefix("##");
  2552. String striped_line = doc_line.strip_edges();
  2553. // Set the read mode.
  2554. if (striped_line.begins_with("@desc:") && p_desc == "") {
  2555. mode = DESC;
  2556. striped_line = striped_line.trim_prefix("@desc:");
  2557. in_codeblock = _in_codeblock(doc_line, in_codeblock);
  2558. } else if (striped_line.begins_with("@tutorial")) {
  2559. int begin_scan = String("@tutorial").length();
  2560. if (begin_scan >= striped_line.length()) {
  2561. continue; // invalid syntax.
  2562. }
  2563. if (striped_line[begin_scan] == ':') { // No title.
  2564. // Syntax: ## @tutorial: https://godotengine.org/ // The title argument is optional.
  2565. title = "";
  2566. link = striped_line.trim_prefix("@tutorial:").strip_edges();
  2567. } else {
  2568. /* Syntax:
  2569. @tutorial ( The Title Here ) : https://the.url/
  2570. ^ open ^ close ^ colon ^ url
  2571. */
  2572. int open_bracket_pos = begin_scan, close_bracket_pos = 0;
  2573. while (open_bracket_pos < striped_line.length() && (striped_line[open_bracket_pos] == ' ' || striped_line[open_bracket_pos] == '\t')) {
  2574. open_bracket_pos++;
  2575. }
  2576. if (open_bracket_pos == striped_line.length() || striped_line[open_bracket_pos++] != '(') {
  2577. continue; // invalid syntax.
  2578. }
  2579. close_bracket_pos = open_bracket_pos;
  2580. while (close_bracket_pos < striped_line.length() && striped_line[close_bracket_pos] != ')') {
  2581. close_bracket_pos++;
  2582. }
  2583. if (close_bracket_pos == striped_line.length()) {
  2584. continue; // invalid syntax.
  2585. }
  2586. int colon_pos = close_bracket_pos + 1;
  2587. while (colon_pos < striped_line.length() && (striped_line[colon_pos] == ' ' || striped_line[colon_pos] == '\t')) {
  2588. colon_pos++;
  2589. }
  2590. if (colon_pos == striped_line.length() || striped_line[colon_pos++] != ':') {
  2591. continue; // invalid syntax.
  2592. }
  2593. title = striped_line.substr(open_bracket_pos, close_bracket_pos - open_bracket_pos).strip_edges();
  2594. link = striped_line.substr(colon_pos).strip_edges();
  2595. }
  2596. mode = TUTORIALS;
  2597. in_codeblock = false;
  2598. } else if (striped_line.is_empty()) {
  2599. continue;
  2600. } else {
  2601. // Tutorial docs are single line, we need a @tag after it.
  2602. if (mode == TUTORIALS) {
  2603. mode = DONE;
  2604. }
  2605. in_codeblock = _in_codeblock(doc_line, in_codeblock, &codeblock_begins);
  2606. }
  2607. if (in_codeblock) {
  2608. int i = 0;
  2609. for (; i < codeblock_begins; i++) {
  2610. if (doc_line[i] != ' ') {
  2611. break;
  2612. }
  2613. }
  2614. doc_line = doc_line.substr(i);
  2615. } else {
  2616. doc_line = striped_line;
  2617. }
  2618. String line_join = (in_codeblock) ? "\n" : " ";
  2619. switch (mode) {
  2620. case BRIEF:
  2621. p_brief = (p_brief.length() == 0) ? doc_line : p_brief + line_join + doc_line;
  2622. break;
  2623. case DESC:
  2624. p_desc = (p_desc.length() == 0) ? doc_line : p_desc + line_join + doc_line;
  2625. break;
  2626. case TUTORIALS:
  2627. p_tutorials.append(Pair<String, String>(title, link));
  2628. break;
  2629. case DONE:
  2630. return;
  2631. }
  2632. }
  2633. }
  2634. #endif // TOOLS_ENABLED
  2635. GDScriptParser::ParseRule *GDScriptParser::get_rule(GDScriptTokenizer::Token::Type p_token_type) {
  2636. // Function table for expression parsing.
  2637. // clang-format destroys the alignment here, so turn off for the table.
  2638. /* clang-format off */
  2639. static ParseRule rules[] = {
  2640. // PREFIX INFIX PRECEDENCE (for infix)
  2641. { nullptr, nullptr, PREC_NONE }, // EMPTY,
  2642. // Basic
  2643. { nullptr, nullptr, PREC_NONE }, // ANNOTATION,
  2644. { &GDScriptParser::parse_identifier, nullptr, PREC_NONE }, // IDENTIFIER,
  2645. { &GDScriptParser::parse_literal, nullptr, PREC_NONE }, // LITERAL,
  2646. // Comparison
  2647. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS,
  2648. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS_EQUAL,
  2649. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER,
  2650. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER_EQUAL,
  2651. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // EQUAL_EQUAL,
  2652. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // BANG_EQUAL,
  2653. // Logical
  2654. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AND,
  2655. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // OR,
  2656. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_not_in_operator, PREC_CONTENT_TEST }, // NOT,
  2657. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AMPERSAND_AMPERSAND,
  2658. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // PIPE_PIPE,
  2659. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // BANG,
  2660. // Bitwise
  2661. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_AND }, // AMPERSAND,
  2662. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_OR }, // PIPE,
  2663. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // TILDE,
  2664. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_XOR }, // CARET,
  2665. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // LESS_LESS,
  2666. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // GREATER_GREATER,
  2667. // Math
  2668. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // PLUS,
  2669. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // MINUS,
  2670. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // STAR,
  2671. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // SLASH,
  2672. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // PERCENT,
  2673. // Assignment
  2674. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // EQUAL,
  2675. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PLUS_EQUAL,
  2676. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // MINUS_EQUAL,
  2677. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_EQUAL,
  2678. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // SLASH_EQUAL,
  2679. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PERCENT_EQUAL,
  2680. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // LESS_LESS_EQUAL,
  2681. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // GREATER_GREATER_EQUAL,
  2682. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // AMPERSAND_EQUAL,
  2683. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PIPE_EQUAL,
  2684. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // CARET_EQUAL,
  2685. // Control flow
  2686. { nullptr, &GDScriptParser::parse_ternary_operator, PREC_TERNARY }, // IF,
  2687. { nullptr, nullptr, PREC_NONE }, // ELIF,
  2688. { nullptr, nullptr, PREC_NONE }, // ELSE,
  2689. { nullptr, nullptr, PREC_NONE }, // FOR,
  2690. { nullptr, nullptr, PREC_NONE }, // WHILE,
  2691. { nullptr, nullptr, PREC_NONE }, // BREAK,
  2692. { nullptr, nullptr, PREC_NONE }, // CONTINUE,
  2693. { nullptr, nullptr, PREC_NONE }, // PASS,
  2694. { nullptr, nullptr, PREC_NONE }, // RETURN,
  2695. { nullptr, nullptr, PREC_NONE }, // MATCH,
  2696. // Keywords
  2697. { nullptr, &GDScriptParser::parse_cast, PREC_CAST }, // AS,
  2698. { nullptr, nullptr, PREC_NONE }, // ASSERT,
  2699. { &GDScriptParser::parse_await, nullptr, PREC_NONE }, // AWAIT,
  2700. { nullptr, nullptr, PREC_NONE }, // BREAKPOINT,
  2701. { nullptr, nullptr, PREC_NONE }, // CLASS,
  2702. { nullptr, nullptr, PREC_NONE }, // CLASS_NAME,
  2703. { nullptr, nullptr, PREC_NONE }, // CONST,
  2704. { nullptr, nullptr, PREC_NONE }, // ENUM,
  2705. { nullptr, nullptr, PREC_NONE }, // EXTENDS,
  2706. { &GDScriptParser::parse_lambda, nullptr, PREC_NONE }, // FUNC,
  2707. { nullptr, &GDScriptParser::parse_binary_operator, PREC_CONTENT_TEST }, // IN,
  2708. { nullptr, &GDScriptParser::parse_binary_operator, PREC_TYPE_TEST }, // IS,
  2709. { nullptr, nullptr, PREC_NONE }, // NAMESPACE,
  2710. { &GDScriptParser::parse_preload, nullptr, PREC_NONE }, // PRELOAD,
  2711. { &GDScriptParser::parse_self, nullptr, PREC_NONE }, // SELF,
  2712. { nullptr, nullptr, PREC_NONE }, // SIGNAL,
  2713. { nullptr, nullptr, PREC_NONE }, // STATIC,
  2714. { &GDScriptParser::parse_call, nullptr, PREC_NONE }, // SUPER,
  2715. { nullptr, nullptr, PREC_NONE }, // TRAIT,
  2716. { nullptr, nullptr, PREC_NONE }, // VAR,
  2717. { nullptr, nullptr, PREC_NONE }, // VOID,
  2718. { nullptr, nullptr, PREC_NONE }, // YIELD,
  2719. // Punctuation
  2720. { &GDScriptParser::parse_array, &GDScriptParser::parse_subscript, PREC_SUBSCRIPT }, // BRACKET_OPEN,
  2721. { nullptr, nullptr, PREC_NONE }, // BRACKET_CLOSE,
  2722. { &GDScriptParser::parse_dictionary, nullptr, PREC_NONE }, // BRACE_OPEN,
  2723. { nullptr, nullptr, PREC_NONE }, // BRACE_CLOSE,
  2724. { &GDScriptParser::parse_grouping, &GDScriptParser::parse_call, PREC_CALL }, // PARENTHESIS_OPEN,
  2725. { nullptr, nullptr, PREC_NONE }, // PARENTHESIS_CLOSE,
  2726. { nullptr, nullptr, PREC_NONE }, // COMMA,
  2727. { nullptr, nullptr, PREC_NONE }, // SEMICOLON,
  2728. { nullptr, &GDScriptParser::parse_attribute, PREC_ATTRIBUTE }, // PERIOD,
  2729. { nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD,
  2730. { nullptr, nullptr, PREC_NONE }, // COLON,
  2731. { &GDScriptParser::parse_get_node, nullptr, PREC_NONE }, // DOLLAR,
  2732. { nullptr, nullptr, PREC_NONE }, // FORWARD_ARROW,
  2733. { nullptr, nullptr, PREC_NONE }, // UNDERSCORE,
  2734. // Whitespace
  2735. { nullptr, nullptr, PREC_NONE }, // NEWLINE,
  2736. { nullptr, nullptr, PREC_NONE }, // INDENT,
  2737. { nullptr, nullptr, PREC_NONE }, // DEDENT,
  2738. // Constants
  2739. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_PI,
  2740. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_TAU,
  2741. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_INF,
  2742. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_NAN,
  2743. // Error message improvement
  2744. { nullptr, nullptr, PREC_NONE }, // VCS_CONFLICT_MARKER,
  2745. { nullptr, nullptr, PREC_NONE }, // BACKTICK,
  2746. { nullptr, &GDScriptParser::parse_invalid_token, PREC_CAST }, // QUESTION_MARK,
  2747. // Special
  2748. { nullptr, nullptr, PREC_NONE }, // ERROR,
  2749. { nullptr, nullptr, PREC_NONE }, // TK_EOF,
  2750. };
  2751. /* clang-format on */
  2752. // Avoid desync.
  2753. static_assert(sizeof(rules) / sizeof(rules[0]) == GDScriptTokenizer::Token::TK_MAX, "Amount of parse rules don't match the amount of token types.");
  2754. // Let's assume this is never invalid, since nothing generates a TK_MAX.
  2755. return &rules[p_token_type];
  2756. }
  2757. bool GDScriptParser::SuiteNode::has_local(const StringName &p_name) const {
  2758. if (locals_indices.has(p_name)) {
  2759. return true;
  2760. }
  2761. if (parent_block != nullptr) {
  2762. return parent_block->has_local(p_name);
  2763. }
  2764. return false;
  2765. }
  2766. const GDScriptParser::SuiteNode::Local &GDScriptParser::SuiteNode::get_local(const StringName &p_name) const {
  2767. if (locals_indices.has(p_name)) {
  2768. return locals[locals_indices[p_name]];
  2769. }
  2770. if (parent_block != nullptr) {
  2771. return parent_block->get_local(p_name);
  2772. }
  2773. return empty;
  2774. }
  2775. bool GDScriptParser::AnnotationNode::apply(GDScriptParser *p_this, Node *p_target) const {
  2776. return (p_this->*(p_this->valid_annotations[name].apply))(this, p_target);
  2777. }
  2778. bool GDScriptParser::AnnotationNode::applies_to(uint32_t p_target_kinds) const {
  2779. return (info->target_kind & p_target_kinds) > 0;
  2780. }
  2781. bool GDScriptParser::validate_annotation_arguments(AnnotationNode *p_annotation) {
  2782. ERR_FAIL_COND_V_MSG(!valid_annotations.has(p_annotation->name), false, vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
  2783. const MethodInfo &info = valid_annotations[p_annotation->name].info;
  2784. if (((info.flags & METHOD_FLAG_VARARG) == 0) && p_annotation->arguments.size() > info.arguments.size()) {
  2785. 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()));
  2786. return false;
  2787. }
  2788. if (p_annotation->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  2789. 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()));
  2790. return false;
  2791. }
  2792. const List<PropertyInfo>::Element *E = info.arguments.front();
  2793. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  2794. ExpressionNode *argument = p_annotation->arguments[i];
  2795. const PropertyInfo &parameter = E->get();
  2796. if (E->next() != nullptr) {
  2797. E = E->next();
  2798. }
  2799. switch (parameter.type) {
  2800. case Variant::STRING:
  2801. case Variant::STRING_NAME:
  2802. case Variant::NODE_PATH:
  2803. // Allow "quote-less strings", as long as they are recognized as identifiers.
  2804. if (argument->type == Node::IDENTIFIER) {
  2805. IdentifierNode *string = static_cast<IdentifierNode *>(argument);
  2806. Callable::CallError error;
  2807. Vector<Variant> args = varray(string->name);
  2808. const Variant *name = args.ptr();
  2809. Variant r;
  2810. Variant::construct(parameter.type, r, &(name), 1, error);
  2811. p_annotation->resolved_arguments.push_back(r);
  2812. if (error.error != Callable::CallError::CALL_OK) {
  2813. push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
  2814. p_annotation->resolved_arguments.remove(p_annotation->resolved_arguments.size() - 1);
  2815. return false;
  2816. }
  2817. break;
  2818. }
  2819. [[fallthrough]];
  2820. default: {
  2821. if (argument->type != Node::LITERAL) {
  2822. push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
  2823. return false;
  2824. }
  2825. Variant value = static_cast<LiteralNode *>(argument)->value;
  2826. if (!Variant::can_convert_strict(value.get_type(), parameter.type)) {
  2827. push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
  2828. return false;
  2829. }
  2830. Callable::CallError error;
  2831. const Variant *args = &value;
  2832. Variant r;
  2833. Variant::construct(parameter.type, r, &(args), 1, error);
  2834. p_annotation->resolved_arguments.push_back(r);
  2835. if (error.error != Callable::CallError::CALL_OK) {
  2836. push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
  2837. p_annotation->resolved_arguments.remove(p_annotation->resolved_arguments.size() - 1);
  2838. return false;
  2839. }
  2840. break;
  2841. }
  2842. }
  2843. }
  2844. return true;
  2845. }
  2846. bool GDScriptParser::tool_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  2847. this->_is_tool = true;
  2848. return true;
  2849. }
  2850. bool GDScriptParser::icon_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  2851. ERR_FAIL_COND_V_MSG(p_node->type != Node::CLASS, false, R"("@icon" annotation can only be applied to classes.)");
  2852. ClassNode *p_class = static_cast<ClassNode *>(p_node);
  2853. p_class->icon_path = p_annotation->resolved_arguments[0];
  2854. return true;
  2855. }
  2856. bool GDScriptParser::onready_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  2857. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, R"("@onready" annotation can only be applied to class variables.)");
  2858. VariableNode *variable = static_cast<VariableNode *>(p_node);
  2859. if (variable->onready) {
  2860. push_error(R"("@onready" annotation can only be used once per variable.)");
  2861. return false;
  2862. }
  2863. variable->onready = true;
  2864. current_class->onready_used = true;
  2865. return true;
  2866. }
  2867. template <PropertyHint t_hint, Variant::Type t_type>
  2868. bool GDScriptParser::export_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  2869. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  2870. VariableNode *variable = static_cast<VariableNode *>(p_node);
  2871. if (variable->exported) {
  2872. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  2873. return false;
  2874. }
  2875. variable->exported = true;
  2876. variable->export_info.type = t_type;
  2877. variable->export_info.hint = t_hint;
  2878. String hint_string;
  2879. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  2880. if (i > 0) {
  2881. hint_string += ",";
  2882. }
  2883. hint_string += String(p_annotation->resolved_arguments[i]);
  2884. }
  2885. variable->export_info.hint_string = hint_string;
  2886. // This is called after tne analyzer is done finding the type, so this should be set here.
  2887. DataType export_type = variable->get_datatype();
  2888. if (p_annotation->name == "@export") {
  2889. if (variable->datatype_specifier == nullptr && variable->initializer == nullptr) {
  2890. push_error(R"(Cannot use simple "@export" annotation with variable without type or initializer, since type can't be inferred.)", p_annotation);
  2891. return false;
  2892. }
  2893. bool is_array = false;
  2894. if (export_type.builtin_type == Variant::ARRAY && export_type.has_container_element_type()) {
  2895. export_type = export_type.get_container_element_type(); // Use inner type for.
  2896. is_array = true;
  2897. }
  2898. if (export_type.is_variant() || export_type.has_no_type()) {
  2899. push_error(R"(Cannot use simple "@export" annotation because the type of the initialized value can't be inferred.)", p_annotation);
  2900. return false;
  2901. }
  2902. switch (export_type.kind) {
  2903. case GDScriptParser::DataType::BUILTIN:
  2904. variable->export_info.type = export_type.builtin_type;
  2905. variable->export_info.hint = PROPERTY_HINT_NONE;
  2906. variable->export_info.hint_string = Variant::get_type_name(export_type.builtin_type);
  2907. break;
  2908. case GDScriptParser::DataType::NATIVE:
  2909. if (ClassDB::is_parent_class(export_type.native_type, "Resource")) {
  2910. variable->export_info.type = Variant::OBJECT;
  2911. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  2912. variable->export_info.hint_string = export_type.native_type;
  2913. } else {
  2914. push_error(R"(Export type can only be built-in, a resource, or an enum.)", variable);
  2915. return false;
  2916. }
  2917. break;
  2918. case GDScriptParser::DataType::ENUM: {
  2919. variable->export_info.type = Variant::INT;
  2920. variable->export_info.hint = PROPERTY_HINT_ENUM;
  2921. String enum_hint_string;
  2922. for (const Map<StringName, int>::Element *E = export_type.enum_values.front(); E; E = E->next()) {
  2923. enum_hint_string += E->key().operator String().camelcase_to_underscore(true).capitalize().xml_escape();
  2924. enum_hint_string += ":";
  2925. enum_hint_string += String::num_int64(E->get()).xml_escape();
  2926. if (E->next()) {
  2927. enum_hint_string += ",";
  2928. }
  2929. }
  2930. variable->export_info.hint_string = enum_hint_string;
  2931. } break;
  2932. default:
  2933. // TODO: Allow custom user resources.
  2934. push_error(R"(Export type can only be built-in, a resource, or an enum.)", variable);
  2935. break;
  2936. }
  2937. if (is_array) {
  2938. String hint_prefix = itos(variable->export_info.type);
  2939. if (variable->export_info.hint) {
  2940. hint_prefix += "/" + itos(variable->export_info.hint);
  2941. }
  2942. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  2943. variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
  2944. variable->export_info.type = Variant::ARRAY;
  2945. }
  2946. } else {
  2947. // Validate variable type with export.
  2948. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != t_type)) {
  2949. // Allow float/int conversion.
  2950. if ((t_type != Variant::FLOAT || export_type.builtin_type != Variant::INT) && (t_type != Variant::INT || export_type.builtin_type != Variant::FLOAT)) {
  2951. 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);
  2952. return false;
  2953. }
  2954. }
  2955. }
  2956. return true;
  2957. }
  2958. bool GDScriptParser::warning_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  2959. ERR_FAIL_V_MSG(false, "Not implemented.");
  2960. }
  2961. template <Multiplayer::RPCMode t_mode>
  2962. bool GDScriptParser::network_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  2963. 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));
  2964. Multiplayer::RPCConfig rpc_config;
  2965. rpc_config.rpc_mode = t_mode;
  2966. if (p_annotation->resolved_arguments.size()) {
  2967. int last = p_annotation->resolved_arguments.size() - 1;
  2968. if (p_annotation->resolved_arguments[last].get_type() == Variant::INT) {
  2969. rpc_config.channel = p_annotation->resolved_arguments[last].operator int();
  2970. last -= 1;
  2971. }
  2972. if (last > 3) {
  2973. 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);
  2974. return false;
  2975. }
  2976. for (int i = last; i >= 0; i--) {
  2977. String mode = p_annotation->resolved_arguments[i].operator String();
  2978. if (mode == "any") {
  2979. rpc_config.rpc_mode = Multiplayer::RPC_MODE_ANY;
  2980. } else if (mode == "auth") {
  2981. rpc_config.rpc_mode = Multiplayer::RPC_MODE_AUTHORITY;
  2982. } else if (mode == "sync") {
  2983. rpc_config.sync = true;
  2984. } else if (mode == "nosync") {
  2985. rpc_config.sync = false;
  2986. } else if (mode == "reliable") {
  2987. rpc_config.transfer_mode = Multiplayer::TRANSFER_MODE_RELIABLE;
  2988. } else if (mode == "unreliable") {
  2989. rpc_config.transfer_mode = Multiplayer::TRANSFER_MODE_UNRELIABLE;
  2990. } else if (mode == "ordered") {
  2991. rpc_config.transfer_mode = Multiplayer::TRANSFER_MODE_ORDERED;
  2992. } else {
  2993. push_error(R"(Invalid RPC argument. Must be one of: 'sync'/'nosync' (local calls), 'any'/'auth' (permission), 'reliable'/'unreliable'/'ordered' (transfer mode).)", p_annotation);
  2994. }
  2995. }
  2996. }
  2997. switch (p_node->type) {
  2998. case Node::FUNCTION: {
  2999. FunctionNode *function = static_cast<FunctionNode *>(p_node);
  3000. if (function->rpc_config.rpc_mode != Multiplayer::RPC_MODE_DISABLED) {
  3001. push_error(R"(RPC annotations can only be used once per function.)", p_annotation);
  3002. return false;
  3003. }
  3004. function->rpc_config = rpc_config;
  3005. break;
  3006. }
  3007. default:
  3008. return false; // Unreachable.
  3009. }
  3010. return true;
  3011. }
  3012. GDScriptParser::DataType GDScriptParser::SuiteNode::Local::get_datatype() const {
  3013. switch (type) {
  3014. case CONSTANT:
  3015. return constant->get_datatype();
  3016. case VARIABLE:
  3017. return variable->get_datatype();
  3018. case PARAMETER:
  3019. return parameter->get_datatype();
  3020. case FOR_VARIABLE:
  3021. case PATTERN_BIND:
  3022. return bind->get_datatype();
  3023. case UNDEFINED:
  3024. return DataType();
  3025. }
  3026. return DataType();
  3027. }
  3028. String GDScriptParser::SuiteNode::Local::get_name() const {
  3029. String name;
  3030. switch (type) {
  3031. case SuiteNode::Local::PARAMETER:
  3032. name = "parameter";
  3033. break;
  3034. case SuiteNode::Local::CONSTANT:
  3035. name = "constant";
  3036. break;
  3037. case SuiteNode::Local::VARIABLE:
  3038. name = "variable";
  3039. break;
  3040. case SuiteNode::Local::FOR_VARIABLE:
  3041. name = "for loop iterator";
  3042. break;
  3043. case SuiteNode::Local::PATTERN_BIND:
  3044. name = "pattern_bind";
  3045. break;
  3046. case SuiteNode::Local::UNDEFINED:
  3047. name = "<undefined>";
  3048. break;
  3049. }
  3050. return name;
  3051. }
  3052. String GDScriptParser::DataType::to_string() const {
  3053. switch (kind) {
  3054. case VARIANT:
  3055. return "Variant";
  3056. case BUILTIN:
  3057. if (builtin_type == Variant::NIL) {
  3058. return "null";
  3059. }
  3060. if (builtin_type == Variant::ARRAY && has_container_element_type()) {
  3061. return vformat("Array[%s]", container_element_type->to_string());
  3062. }
  3063. return Variant::get_type_name(builtin_type);
  3064. case NATIVE:
  3065. if (is_meta_type) {
  3066. return GDScriptNativeClass::get_class_static();
  3067. }
  3068. return native_type.operator String();
  3069. case CLASS:
  3070. if (is_meta_type) {
  3071. return GDScript::get_class_static();
  3072. }
  3073. if (class_type->identifier != nullptr) {
  3074. return class_type->identifier->name.operator String();
  3075. }
  3076. return class_type->fqcn;
  3077. case SCRIPT: {
  3078. if (is_meta_type) {
  3079. return script_type->get_class_name().operator String();
  3080. }
  3081. String name = script_type->get_name();
  3082. if (!name.is_empty()) {
  3083. return name;
  3084. }
  3085. name = script_path;
  3086. if (!name.is_empty()) {
  3087. return name;
  3088. }
  3089. return native_type.operator String();
  3090. }
  3091. case ENUM:
  3092. return enum_type.operator String() + " (enum)";
  3093. case ENUM_VALUE:
  3094. return enum_type.operator String() + " (enum value)";
  3095. case UNRESOLVED:
  3096. return "<unresolved type>";
  3097. }
  3098. ERR_FAIL_V_MSG("<unresolved type", "Kind set outside the enum range.");
  3099. }
  3100. /*---------- PRETTY PRINT FOR DEBUG ----------*/
  3101. #ifdef DEBUG_ENABLED
  3102. void GDScriptParser::TreePrinter::increase_indent() {
  3103. indent_level++;
  3104. indent = "";
  3105. for (int i = 0; i < indent_level * 4; i++) {
  3106. if (i % 4 == 0) {
  3107. indent += "|";
  3108. } else {
  3109. indent += " ";
  3110. }
  3111. }
  3112. }
  3113. void GDScriptParser::TreePrinter::decrease_indent() {
  3114. indent_level--;
  3115. indent = "";
  3116. for (int i = 0; i < indent_level * 4; i++) {
  3117. if (i % 4 == 0) {
  3118. indent += "|";
  3119. } else {
  3120. indent += " ";
  3121. }
  3122. }
  3123. }
  3124. void GDScriptParser::TreePrinter::push_line(const String &p_line) {
  3125. if (!p_line.is_empty()) {
  3126. push_text(p_line);
  3127. }
  3128. printed += "\n";
  3129. pending_indent = true;
  3130. }
  3131. void GDScriptParser::TreePrinter::push_text(const String &p_text) {
  3132. if (pending_indent) {
  3133. printed += indent;
  3134. pending_indent = false;
  3135. }
  3136. printed += p_text;
  3137. }
  3138. void GDScriptParser::TreePrinter::print_annotation(const AnnotationNode *p_annotation) {
  3139. push_text(p_annotation->name);
  3140. push_text(" (");
  3141. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  3142. if (i > 0) {
  3143. push_text(" , ");
  3144. }
  3145. print_expression(p_annotation->arguments[i]);
  3146. }
  3147. push_line(")");
  3148. }
  3149. void GDScriptParser::TreePrinter::print_array(ArrayNode *p_array) {
  3150. push_text("[ ");
  3151. for (int i = 0; i < p_array->elements.size(); i++) {
  3152. if (i > 0) {
  3153. push_text(" , ");
  3154. }
  3155. print_expression(p_array->elements[i]);
  3156. }
  3157. push_text(" ]");
  3158. }
  3159. void GDScriptParser::TreePrinter::print_assert(AssertNode *p_assert) {
  3160. push_text("Assert ( ");
  3161. print_expression(p_assert->condition);
  3162. push_line(" )");
  3163. }
  3164. void GDScriptParser::TreePrinter::print_assignment(AssignmentNode *p_assignment) {
  3165. switch (p_assignment->assignee->type) {
  3166. case Node::IDENTIFIER:
  3167. print_identifier(static_cast<IdentifierNode *>(p_assignment->assignee));
  3168. break;
  3169. case Node::SUBSCRIPT:
  3170. print_subscript(static_cast<SubscriptNode *>(p_assignment->assignee));
  3171. break;
  3172. default:
  3173. break; // Unreachable.
  3174. }
  3175. push_text(" ");
  3176. switch (p_assignment->operation) {
  3177. case AssignmentNode::OP_ADDITION:
  3178. push_text("+");
  3179. break;
  3180. case AssignmentNode::OP_SUBTRACTION:
  3181. push_text("-");
  3182. break;
  3183. case AssignmentNode::OP_MULTIPLICATION:
  3184. push_text("*");
  3185. break;
  3186. case AssignmentNode::OP_DIVISION:
  3187. push_text("/");
  3188. break;
  3189. case AssignmentNode::OP_MODULO:
  3190. push_text("%");
  3191. break;
  3192. case AssignmentNode::OP_BIT_SHIFT_LEFT:
  3193. push_text("<<");
  3194. break;
  3195. case AssignmentNode::OP_BIT_SHIFT_RIGHT:
  3196. push_text(">>");
  3197. break;
  3198. case AssignmentNode::OP_BIT_AND:
  3199. push_text("&");
  3200. break;
  3201. case AssignmentNode::OP_BIT_OR:
  3202. push_text("|");
  3203. break;
  3204. case AssignmentNode::OP_BIT_XOR:
  3205. push_text("^");
  3206. break;
  3207. case AssignmentNode::OP_NONE:
  3208. break;
  3209. }
  3210. push_text("= ");
  3211. print_expression(p_assignment->assigned_value);
  3212. push_line();
  3213. }
  3214. void GDScriptParser::TreePrinter::print_await(AwaitNode *p_await) {
  3215. push_text("Await ");
  3216. print_expression(p_await->to_await);
  3217. }
  3218. void GDScriptParser::TreePrinter::print_binary_op(BinaryOpNode *p_binary_op) {
  3219. // Surround in parenthesis for disambiguation.
  3220. push_text("(");
  3221. print_expression(p_binary_op->left_operand);
  3222. switch (p_binary_op->operation) {
  3223. case BinaryOpNode::OP_ADDITION:
  3224. push_text(" + ");
  3225. break;
  3226. case BinaryOpNode::OP_SUBTRACTION:
  3227. push_text(" - ");
  3228. break;
  3229. case BinaryOpNode::OP_MULTIPLICATION:
  3230. push_text(" * ");
  3231. break;
  3232. case BinaryOpNode::OP_DIVISION:
  3233. push_text(" / ");
  3234. break;
  3235. case BinaryOpNode::OP_MODULO:
  3236. push_text(" % ");
  3237. break;
  3238. case BinaryOpNode::OP_BIT_LEFT_SHIFT:
  3239. push_text(" << ");
  3240. break;
  3241. case BinaryOpNode::OP_BIT_RIGHT_SHIFT:
  3242. push_text(" >> ");
  3243. break;
  3244. case BinaryOpNode::OP_BIT_AND:
  3245. push_text(" & ");
  3246. break;
  3247. case BinaryOpNode::OP_BIT_OR:
  3248. push_text(" | ");
  3249. break;
  3250. case BinaryOpNode::OP_BIT_XOR:
  3251. push_text(" ^ ");
  3252. break;
  3253. case BinaryOpNode::OP_LOGIC_AND:
  3254. push_text(" AND ");
  3255. break;
  3256. case BinaryOpNode::OP_LOGIC_OR:
  3257. push_text(" OR ");
  3258. break;
  3259. case BinaryOpNode::OP_TYPE_TEST:
  3260. push_text(" IS ");
  3261. break;
  3262. case BinaryOpNode::OP_CONTENT_TEST:
  3263. push_text(" IN ");
  3264. break;
  3265. case BinaryOpNode::OP_COMP_EQUAL:
  3266. push_text(" == ");
  3267. break;
  3268. case BinaryOpNode::OP_COMP_NOT_EQUAL:
  3269. push_text(" != ");
  3270. break;
  3271. case BinaryOpNode::OP_COMP_LESS:
  3272. push_text(" < ");
  3273. break;
  3274. case BinaryOpNode::OP_COMP_LESS_EQUAL:
  3275. push_text(" <= ");
  3276. break;
  3277. case BinaryOpNode::OP_COMP_GREATER:
  3278. push_text(" > ");
  3279. break;
  3280. case BinaryOpNode::OP_COMP_GREATER_EQUAL:
  3281. push_text(" >= ");
  3282. break;
  3283. }
  3284. print_expression(p_binary_op->right_operand);
  3285. // Surround in parenthesis for disambiguation.
  3286. push_text(")");
  3287. }
  3288. void GDScriptParser::TreePrinter::print_call(CallNode *p_call) {
  3289. if (p_call->is_super) {
  3290. push_text("super");
  3291. if (p_call->callee != nullptr) {
  3292. push_text(".");
  3293. print_expression(p_call->callee);
  3294. }
  3295. } else {
  3296. print_expression(p_call->callee);
  3297. }
  3298. push_text("( ");
  3299. for (int i = 0; i < p_call->arguments.size(); i++) {
  3300. if (i > 0) {
  3301. push_text(" , ");
  3302. }
  3303. print_expression(p_call->arguments[i]);
  3304. }
  3305. push_text(" )");
  3306. }
  3307. void GDScriptParser::TreePrinter::print_cast(CastNode *p_cast) {
  3308. print_expression(p_cast->operand);
  3309. push_text(" AS ");
  3310. print_type(p_cast->cast_type);
  3311. }
  3312. void GDScriptParser::TreePrinter::print_class(ClassNode *p_class) {
  3313. push_text("Class ");
  3314. if (p_class->identifier == nullptr) {
  3315. push_text("<unnamed>");
  3316. } else {
  3317. print_identifier(p_class->identifier);
  3318. }
  3319. if (p_class->extends_used) {
  3320. bool first = true;
  3321. push_text(" Extends ");
  3322. if (!p_class->extends_path.is_empty()) {
  3323. push_text(vformat(R"("%s")", p_class->extends_path));
  3324. first = false;
  3325. }
  3326. for (int i = 0; i < p_class->extends.size(); i++) {
  3327. if (!first) {
  3328. push_text(".");
  3329. } else {
  3330. first = false;
  3331. }
  3332. push_text(p_class->extends[i]);
  3333. }
  3334. }
  3335. push_line(" :");
  3336. increase_indent();
  3337. for (int i = 0; i < p_class->members.size(); i++) {
  3338. const ClassNode::Member &m = p_class->members[i];
  3339. switch (m.type) {
  3340. case ClassNode::Member::CLASS:
  3341. print_class(m.m_class);
  3342. break;
  3343. case ClassNode::Member::VARIABLE:
  3344. print_variable(m.variable);
  3345. break;
  3346. case ClassNode::Member::CONSTANT:
  3347. print_constant(m.constant);
  3348. break;
  3349. case ClassNode::Member::SIGNAL:
  3350. print_signal(m.signal);
  3351. break;
  3352. case ClassNode::Member::FUNCTION:
  3353. print_function(m.function);
  3354. break;
  3355. case ClassNode::Member::ENUM:
  3356. print_enum(m.m_enum);
  3357. break;
  3358. case ClassNode::Member::ENUM_VALUE:
  3359. break; // Nothing. Will be printed by enum.
  3360. case ClassNode::Member::UNDEFINED:
  3361. push_line("<unknown member>");
  3362. break;
  3363. }
  3364. }
  3365. decrease_indent();
  3366. }
  3367. void GDScriptParser::TreePrinter::print_constant(ConstantNode *p_constant) {
  3368. push_text("Constant ");
  3369. print_identifier(p_constant->identifier);
  3370. increase_indent();
  3371. push_line();
  3372. push_text("= ");
  3373. if (p_constant->initializer == nullptr) {
  3374. push_text("<missing value>");
  3375. } else {
  3376. print_expression(p_constant->initializer);
  3377. }
  3378. decrease_indent();
  3379. push_line();
  3380. }
  3381. void GDScriptParser::TreePrinter::print_dictionary(DictionaryNode *p_dictionary) {
  3382. push_line("{");
  3383. increase_indent();
  3384. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  3385. print_expression(p_dictionary->elements[i].key);
  3386. if (p_dictionary->style == DictionaryNode::PYTHON_DICT) {
  3387. push_text(" : ");
  3388. } else {
  3389. push_text(" = ");
  3390. }
  3391. print_expression(p_dictionary->elements[i].value);
  3392. push_line(" ,");
  3393. }
  3394. decrease_indent();
  3395. push_text("}");
  3396. }
  3397. void GDScriptParser::TreePrinter::print_expression(ExpressionNode *p_expression) {
  3398. if (p_expression == nullptr) {
  3399. push_text("<invalid expression>");
  3400. return;
  3401. }
  3402. switch (p_expression->type) {
  3403. case Node::ARRAY:
  3404. print_array(static_cast<ArrayNode *>(p_expression));
  3405. break;
  3406. case Node::ASSIGNMENT:
  3407. print_assignment(static_cast<AssignmentNode *>(p_expression));
  3408. break;
  3409. case Node::AWAIT:
  3410. print_await(static_cast<AwaitNode *>(p_expression));
  3411. break;
  3412. case Node::BINARY_OPERATOR:
  3413. print_binary_op(static_cast<BinaryOpNode *>(p_expression));
  3414. break;
  3415. case Node::CALL:
  3416. print_call(static_cast<CallNode *>(p_expression));
  3417. break;
  3418. case Node::CAST:
  3419. print_cast(static_cast<CastNode *>(p_expression));
  3420. break;
  3421. case Node::DICTIONARY:
  3422. print_dictionary(static_cast<DictionaryNode *>(p_expression));
  3423. break;
  3424. case Node::GET_NODE:
  3425. print_get_node(static_cast<GetNodeNode *>(p_expression));
  3426. break;
  3427. case Node::IDENTIFIER:
  3428. print_identifier(static_cast<IdentifierNode *>(p_expression));
  3429. break;
  3430. case Node::LAMBDA:
  3431. print_lambda(static_cast<LambdaNode *>(p_expression));
  3432. break;
  3433. case Node::LITERAL:
  3434. print_literal(static_cast<LiteralNode *>(p_expression));
  3435. break;
  3436. case Node::PRELOAD:
  3437. print_preload(static_cast<PreloadNode *>(p_expression));
  3438. break;
  3439. case Node::SELF:
  3440. print_self(static_cast<SelfNode *>(p_expression));
  3441. break;
  3442. case Node::SUBSCRIPT:
  3443. print_subscript(static_cast<SubscriptNode *>(p_expression));
  3444. break;
  3445. case Node::TERNARY_OPERATOR:
  3446. print_ternary_op(static_cast<TernaryOpNode *>(p_expression));
  3447. break;
  3448. case Node::UNARY_OPERATOR:
  3449. print_unary_op(static_cast<UnaryOpNode *>(p_expression));
  3450. break;
  3451. default:
  3452. push_text(vformat("<unknown expression %d>", p_expression->type));
  3453. break;
  3454. }
  3455. }
  3456. void GDScriptParser::TreePrinter::print_enum(EnumNode *p_enum) {
  3457. push_text("Enum ");
  3458. if (p_enum->identifier != nullptr) {
  3459. print_identifier(p_enum->identifier);
  3460. } else {
  3461. push_text("<unnamed>");
  3462. }
  3463. push_line(" {");
  3464. increase_indent();
  3465. for (int i = 0; i < p_enum->values.size(); i++) {
  3466. const EnumNode::Value &item = p_enum->values[i];
  3467. print_identifier(item.identifier);
  3468. push_text(" = ");
  3469. push_text(itos(item.value));
  3470. push_line(" ,");
  3471. }
  3472. decrease_indent();
  3473. push_line("}");
  3474. }
  3475. void GDScriptParser::TreePrinter::print_for(ForNode *p_for) {
  3476. push_text("For ");
  3477. print_identifier(p_for->variable);
  3478. push_text(" IN ");
  3479. print_expression(p_for->list);
  3480. push_line(" :");
  3481. increase_indent();
  3482. print_suite(p_for->loop);
  3483. decrease_indent();
  3484. }
  3485. void GDScriptParser::TreePrinter::print_function(FunctionNode *p_function, const String &p_context) {
  3486. for (const AnnotationNode *E : p_function->annotations) {
  3487. print_annotation(E);
  3488. }
  3489. push_text(p_context);
  3490. push_text(" ");
  3491. if (p_function->identifier) {
  3492. print_identifier(p_function->identifier);
  3493. } else {
  3494. push_text("<anonymous>");
  3495. }
  3496. push_text("( ");
  3497. for (int i = 0; i < p_function->parameters.size(); i++) {
  3498. if (i > 0) {
  3499. push_text(" , ");
  3500. }
  3501. print_parameter(p_function->parameters[i]);
  3502. }
  3503. push_line(" ) :");
  3504. increase_indent();
  3505. print_suite(p_function->body);
  3506. decrease_indent();
  3507. }
  3508. void GDScriptParser::TreePrinter::print_get_node(GetNodeNode *p_get_node) {
  3509. push_text("$");
  3510. if (p_get_node->string != nullptr) {
  3511. print_literal(p_get_node->string);
  3512. } else {
  3513. for (int i = 0; i < p_get_node->chain.size(); i++) {
  3514. if (i > 0) {
  3515. push_text("/");
  3516. }
  3517. print_identifier(p_get_node->chain[i]);
  3518. }
  3519. }
  3520. }
  3521. void GDScriptParser::TreePrinter::print_identifier(IdentifierNode *p_identifier) {
  3522. push_text(p_identifier->name);
  3523. }
  3524. void GDScriptParser::TreePrinter::print_if(IfNode *p_if, bool p_is_elif) {
  3525. if (p_is_elif) {
  3526. push_text("Elif ");
  3527. } else {
  3528. push_text("If ");
  3529. }
  3530. print_expression(p_if->condition);
  3531. push_line(" :");
  3532. increase_indent();
  3533. print_suite(p_if->true_block);
  3534. decrease_indent();
  3535. // FIXME: Properly detect "elif" blocks.
  3536. if (p_if->false_block != nullptr) {
  3537. push_line("Else :");
  3538. increase_indent();
  3539. print_suite(p_if->false_block);
  3540. decrease_indent();
  3541. }
  3542. }
  3543. void GDScriptParser::TreePrinter::print_lambda(LambdaNode *p_lambda) {
  3544. print_function(p_lambda->function, "Lambda");
  3545. push_text("| captures [ ");
  3546. for (int i = 0; i < p_lambda->captures.size(); i++) {
  3547. if (i > 0) {
  3548. push_text(" , ");
  3549. }
  3550. push_text(p_lambda->captures[i]->name.operator String());
  3551. }
  3552. push_line(" ]");
  3553. }
  3554. void GDScriptParser::TreePrinter::print_literal(LiteralNode *p_literal) {
  3555. // Prefix for string types.
  3556. switch (p_literal->value.get_type()) {
  3557. case Variant::NODE_PATH:
  3558. push_text("^\"");
  3559. break;
  3560. case Variant::STRING:
  3561. push_text("\"");
  3562. break;
  3563. case Variant::STRING_NAME:
  3564. push_text("&\"");
  3565. break;
  3566. default:
  3567. break;
  3568. }
  3569. push_text(p_literal->value);
  3570. // Suffix for string types.
  3571. switch (p_literal->value.get_type()) {
  3572. case Variant::NODE_PATH:
  3573. case Variant::STRING:
  3574. case Variant::STRING_NAME:
  3575. push_text("\"");
  3576. break;
  3577. default:
  3578. break;
  3579. }
  3580. }
  3581. void GDScriptParser::TreePrinter::print_match(MatchNode *p_match) {
  3582. push_text("Match ");
  3583. print_expression(p_match->test);
  3584. push_line(" :");
  3585. increase_indent();
  3586. for (int i = 0; i < p_match->branches.size(); i++) {
  3587. print_match_branch(p_match->branches[i]);
  3588. }
  3589. decrease_indent();
  3590. }
  3591. void GDScriptParser::TreePrinter::print_match_branch(MatchBranchNode *p_match_branch) {
  3592. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  3593. if (i > 0) {
  3594. push_text(" , ");
  3595. }
  3596. print_match_pattern(p_match_branch->patterns[i]);
  3597. }
  3598. push_line(" :");
  3599. increase_indent();
  3600. print_suite(p_match_branch->block);
  3601. decrease_indent();
  3602. }
  3603. void GDScriptParser::TreePrinter::print_match_pattern(PatternNode *p_match_pattern) {
  3604. switch (p_match_pattern->pattern_type) {
  3605. case PatternNode::PT_LITERAL:
  3606. print_literal(p_match_pattern->literal);
  3607. break;
  3608. case PatternNode::PT_WILDCARD:
  3609. push_text("_");
  3610. break;
  3611. case PatternNode::PT_REST:
  3612. push_text("..");
  3613. break;
  3614. case PatternNode::PT_BIND:
  3615. push_text("Var ");
  3616. print_identifier(p_match_pattern->bind);
  3617. break;
  3618. case PatternNode::PT_EXPRESSION:
  3619. print_expression(p_match_pattern->expression);
  3620. break;
  3621. case PatternNode::PT_ARRAY:
  3622. push_text("[ ");
  3623. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  3624. if (i > 0) {
  3625. push_text(" , ");
  3626. }
  3627. print_match_pattern(p_match_pattern->array[i]);
  3628. }
  3629. push_text(" ]");
  3630. break;
  3631. case PatternNode::PT_DICTIONARY:
  3632. push_text("{ ");
  3633. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  3634. if (i > 0) {
  3635. push_text(" , ");
  3636. }
  3637. if (p_match_pattern->dictionary[i].key != nullptr) {
  3638. // Key can be null for rest pattern.
  3639. print_expression(p_match_pattern->dictionary[i].key);
  3640. push_text(" : ");
  3641. }
  3642. print_match_pattern(p_match_pattern->dictionary[i].value_pattern);
  3643. }
  3644. push_text(" }");
  3645. break;
  3646. }
  3647. }
  3648. void GDScriptParser::TreePrinter::print_parameter(ParameterNode *p_parameter) {
  3649. print_identifier(p_parameter->identifier);
  3650. if (p_parameter->datatype_specifier != nullptr) {
  3651. push_text(" : ");
  3652. print_type(p_parameter->datatype_specifier);
  3653. }
  3654. if (p_parameter->default_value != nullptr) {
  3655. push_text(" = ");
  3656. print_expression(p_parameter->default_value);
  3657. }
  3658. }
  3659. void GDScriptParser::TreePrinter::print_preload(PreloadNode *p_preload) {
  3660. push_text(R"(Preload ( ")");
  3661. push_text(p_preload->resolved_path);
  3662. push_text(R"(" )");
  3663. }
  3664. void GDScriptParser::TreePrinter::print_return(ReturnNode *p_return) {
  3665. push_text("Return");
  3666. if (p_return->return_value != nullptr) {
  3667. push_text(" ");
  3668. print_expression(p_return->return_value);
  3669. }
  3670. push_line();
  3671. }
  3672. void GDScriptParser::TreePrinter::print_self(SelfNode *p_self) {
  3673. push_text("Self(");
  3674. if (p_self->current_class->identifier != nullptr) {
  3675. print_identifier(p_self->current_class->identifier);
  3676. } else {
  3677. push_text("<main class>");
  3678. }
  3679. push_text(")");
  3680. }
  3681. void GDScriptParser::TreePrinter::print_signal(SignalNode *p_signal) {
  3682. push_text("Signal ");
  3683. print_identifier(p_signal->identifier);
  3684. push_text("( ");
  3685. for (int i = 0; i < p_signal->parameters.size(); i++) {
  3686. print_parameter(p_signal->parameters[i]);
  3687. }
  3688. push_line(" )");
  3689. }
  3690. void GDScriptParser::TreePrinter::print_subscript(SubscriptNode *p_subscript) {
  3691. print_expression(p_subscript->base);
  3692. if (p_subscript->is_attribute) {
  3693. push_text(".");
  3694. print_identifier(p_subscript->attribute);
  3695. } else {
  3696. push_text("[ ");
  3697. print_expression(p_subscript->index);
  3698. push_text(" ]");
  3699. }
  3700. }
  3701. void GDScriptParser::TreePrinter::print_statement(Node *p_statement) {
  3702. switch (p_statement->type) {
  3703. case Node::ASSERT:
  3704. print_assert(static_cast<AssertNode *>(p_statement));
  3705. break;
  3706. case Node::VARIABLE:
  3707. print_variable(static_cast<VariableNode *>(p_statement));
  3708. break;
  3709. case Node::CONSTANT:
  3710. print_constant(static_cast<ConstantNode *>(p_statement));
  3711. break;
  3712. case Node::IF:
  3713. print_if(static_cast<IfNode *>(p_statement));
  3714. break;
  3715. case Node::FOR:
  3716. print_for(static_cast<ForNode *>(p_statement));
  3717. break;
  3718. case Node::WHILE:
  3719. print_while(static_cast<WhileNode *>(p_statement));
  3720. break;
  3721. case Node::MATCH:
  3722. print_match(static_cast<MatchNode *>(p_statement));
  3723. break;
  3724. case Node::RETURN:
  3725. print_return(static_cast<ReturnNode *>(p_statement));
  3726. break;
  3727. case Node::BREAK:
  3728. push_line("Break");
  3729. break;
  3730. case Node::CONTINUE:
  3731. push_line("Continue");
  3732. break;
  3733. case Node::PASS:
  3734. push_line("Pass");
  3735. break;
  3736. case Node::BREAKPOINT:
  3737. push_line("Breakpoint");
  3738. break;
  3739. case Node::ASSIGNMENT:
  3740. print_assignment(static_cast<AssignmentNode *>(p_statement));
  3741. break;
  3742. default:
  3743. if (p_statement->is_expression()) {
  3744. print_expression(static_cast<ExpressionNode *>(p_statement));
  3745. push_line();
  3746. } else {
  3747. push_line(vformat("<unknown statement %d>", p_statement->type));
  3748. }
  3749. break;
  3750. }
  3751. }
  3752. void GDScriptParser::TreePrinter::print_suite(SuiteNode *p_suite) {
  3753. for (int i = 0; i < p_suite->statements.size(); i++) {
  3754. print_statement(p_suite->statements[i]);
  3755. }
  3756. }
  3757. void GDScriptParser::TreePrinter::print_ternary_op(TernaryOpNode *p_ternary_op) {
  3758. // Surround in parenthesis for disambiguation.
  3759. push_text("(");
  3760. print_expression(p_ternary_op->true_expr);
  3761. push_text(") IF (");
  3762. print_expression(p_ternary_op->condition);
  3763. push_text(") ELSE (");
  3764. print_expression(p_ternary_op->false_expr);
  3765. push_text(")");
  3766. }
  3767. void GDScriptParser::TreePrinter::print_type(TypeNode *p_type) {
  3768. if (p_type->type_chain.is_empty()) {
  3769. push_text("Void");
  3770. } else {
  3771. for (int i = 0; i < p_type->type_chain.size(); i++) {
  3772. if (i > 0) {
  3773. push_text(".");
  3774. }
  3775. print_identifier(p_type->type_chain[i]);
  3776. }
  3777. }
  3778. }
  3779. void GDScriptParser::TreePrinter::print_unary_op(UnaryOpNode *p_unary_op) {
  3780. // Surround in parenthesis for disambiguation.
  3781. push_text("(");
  3782. switch (p_unary_op->operation) {
  3783. case UnaryOpNode::OP_POSITIVE:
  3784. push_text("+");
  3785. break;
  3786. case UnaryOpNode::OP_NEGATIVE:
  3787. push_text("-");
  3788. break;
  3789. case UnaryOpNode::OP_LOGIC_NOT:
  3790. push_text("NOT");
  3791. break;
  3792. case UnaryOpNode::OP_COMPLEMENT:
  3793. push_text("~");
  3794. break;
  3795. }
  3796. print_expression(p_unary_op->operand);
  3797. // Surround in parenthesis for disambiguation.
  3798. push_text(")");
  3799. }
  3800. void GDScriptParser::TreePrinter::print_variable(VariableNode *p_variable) {
  3801. for (const AnnotationNode *E : p_variable->annotations) {
  3802. print_annotation(E);
  3803. }
  3804. push_text("Variable ");
  3805. print_identifier(p_variable->identifier);
  3806. push_text(" : ");
  3807. if (p_variable->datatype_specifier != nullptr) {
  3808. print_type(p_variable->datatype_specifier);
  3809. } else if (p_variable->infer_datatype) {
  3810. push_text("<inferred type>");
  3811. } else {
  3812. push_text("Variant");
  3813. }
  3814. increase_indent();
  3815. push_line();
  3816. push_text("= ");
  3817. if (p_variable->initializer == nullptr) {
  3818. push_text("<default value>");
  3819. } else {
  3820. print_expression(p_variable->initializer);
  3821. }
  3822. push_line();
  3823. if (p_variable->property != VariableNode::PROP_NONE) {
  3824. if (p_variable->getter != nullptr) {
  3825. push_text("Get");
  3826. if (p_variable->property == VariableNode::PROP_INLINE) {
  3827. push_line(":");
  3828. increase_indent();
  3829. print_suite(p_variable->getter);
  3830. decrease_indent();
  3831. } else {
  3832. push_line(" =");
  3833. increase_indent();
  3834. print_identifier(p_variable->getter_pointer);
  3835. push_line();
  3836. decrease_indent();
  3837. }
  3838. }
  3839. if (p_variable->setter != nullptr) {
  3840. push_text("Set (");
  3841. if (p_variable->property == VariableNode::PROP_INLINE) {
  3842. if (p_variable->setter_parameter != nullptr) {
  3843. print_identifier(p_variable->setter_parameter);
  3844. } else {
  3845. push_text("<missing>");
  3846. }
  3847. push_line("):");
  3848. increase_indent();
  3849. print_suite(p_variable->setter);
  3850. decrease_indent();
  3851. } else {
  3852. push_line(" =");
  3853. increase_indent();
  3854. print_identifier(p_variable->setter_pointer);
  3855. push_line();
  3856. decrease_indent();
  3857. }
  3858. }
  3859. }
  3860. decrease_indent();
  3861. push_line();
  3862. }
  3863. void GDScriptParser::TreePrinter::print_while(WhileNode *p_while) {
  3864. push_text("While ");
  3865. print_expression(p_while->condition);
  3866. push_line(" :");
  3867. increase_indent();
  3868. print_suite(p_while->loop);
  3869. decrease_indent();
  3870. }
  3871. void GDScriptParser::TreePrinter::print_tree(const GDScriptParser &p_parser) {
  3872. ERR_FAIL_COND_MSG(p_parser.get_tree() == nullptr, "Parse the code before printing the parse tree.");
  3873. if (p_parser.is_tool()) {
  3874. push_line("@tool");
  3875. }
  3876. if (!p_parser.get_tree()->icon_path.is_empty()) {
  3877. push_text(R"(@icon (")");
  3878. push_text(p_parser.get_tree()->icon_path);
  3879. push_line("\")");
  3880. }
  3881. print_class(p_parser.get_tree());
  3882. print_line(printed);
  3883. }
  3884. #endif // DEBUG_ENABLED