gdscript_parser.cpp 171 KB

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