gdscript_parser.cpp 156 KB

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