gdscript_parser.cpp 176 KB

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