gdscript_parser.cpp 161 KB

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