gdscript_parser.cpp 161 KB

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