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