gdscript_parser.cpp 147 KB

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