gdscript_parser.cpp 148 KB

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