gdscript_parser.cpp 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223
  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));
  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. bool multiline = false;
  1336. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  1337. multiline = true;
  1338. }
  1339. if (multiline) {
  1340. if (!consume(GDScriptTokenizer::Token::INDENT, vformat(R"(Expected indented block after %s.)", p_context))) {
  1341. current_suite = suite->parent_block;
  1342. complete_extents(suite);
  1343. return suite;
  1344. }
  1345. }
  1346. reset_extents(suite, current);
  1347. int error_count = 0;
  1348. do {
  1349. if (is_at_end() || (!multiline && previous.type == GDScriptTokenizer::Token::SEMICOLON && check(GDScriptTokenizer::Token::NEWLINE))) {
  1350. break;
  1351. }
  1352. Node *statement = parse_statement();
  1353. if (statement == nullptr) {
  1354. if (error_count++ > 100) {
  1355. push_error("Too many statement errors.", suite);
  1356. break;
  1357. }
  1358. continue;
  1359. }
  1360. suite->statements.push_back(statement);
  1361. // Register locals.
  1362. switch (statement->type) {
  1363. case Node::VARIABLE: {
  1364. VariableNode *variable = static_cast<VariableNode *>(statement);
  1365. const SuiteNode::Local &local = current_suite->get_local(variable->identifier->name);
  1366. if (local.type != SuiteNode::Local::UNDEFINED) {
  1367. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), variable->identifier->name), variable->identifier);
  1368. }
  1369. current_suite->add_local(variable, current_function);
  1370. break;
  1371. }
  1372. case Node::CONSTANT: {
  1373. ConstantNode *constant = static_cast<ConstantNode *>(statement);
  1374. const SuiteNode::Local &local = current_suite->get_local(constant->identifier->name);
  1375. if (local.type != SuiteNode::Local::UNDEFINED) {
  1376. String name;
  1377. if (local.type == SuiteNode::Local::CONSTANT) {
  1378. name = "constant";
  1379. } else {
  1380. name = "variable";
  1381. }
  1382. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", name, constant->identifier->name), constant->identifier);
  1383. }
  1384. current_suite->add_local(constant, current_function);
  1385. break;
  1386. }
  1387. default:
  1388. break;
  1389. }
  1390. } while ((multiline || previous.type == GDScriptTokenizer::Token::SEMICOLON) && !check(GDScriptTokenizer::Token::DEDENT) && !lambda_ended && !is_at_end());
  1391. complete_extents(suite);
  1392. if (multiline) {
  1393. if (!lambda_ended) {
  1394. consume(GDScriptTokenizer::Token::DEDENT, vformat(R"(Missing unindent at the end of %s.)", p_context));
  1395. } else {
  1396. match(GDScriptTokenizer::Token::DEDENT);
  1397. }
  1398. } else if (previous.type == GDScriptTokenizer::Token::SEMICOLON) {
  1399. consume(GDScriptTokenizer::Token::NEWLINE, vformat(R"(Expected newline after ";" at the end of %s.)", p_context));
  1400. }
  1401. if (p_for_lambda) {
  1402. lambda_ended = true;
  1403. }
  1404. current_suite = suite->parent_block;
  1405. return suite;
  1406. }
  1407. GDScriptParser::Node *GDScriptParser::parse_statement() {
  1408. Node *result = nullptr;
  1409. #ifdef DEBUG_ENABLED
  1410. bool unreachable = current_suite->has_return && !current_suite->has_unreachable_code;
  1411. #endif
  1412. bool is_annotation = false;
  1413. switch (current.type) {
  1414. case GDScriptTokenizer::Token::PASS:
  1415. advance();
  1416. result = alloc_node<PassNode>();
  1417. complete_extents(result);
  1418. end_statement(R"("pass")");
  1419. break;
  1420. case GDScriptTokenizer::Token::VAR:
  1421. advance();
  1422. result = parse_variable(false, false);
  1423. break;
  1424. case GDScriptTokenizer::Token::CONST:
  1425. advance();
  1426. result = parse_constant(false);
  1427. break;
  1428. case GDScriptTokenizer::Token::IF:
  1429. advance();
  1430. result = parse_if();
  1431. break;
  1432. case GDScriptTokenizer::Token::FOR:
  1433. advance();
  1434. result = parse_for();
  1435. break;
  1436. case GDScriptTokenizer::Token::WHILE:
  1437. advance();
  1438. result = parse_while();
  1439. break;
  1440. case GDScriptTokenizer::Token::MATCH:
  1441. advance();
  1442. result = parse_match();
  1443. break;
  1444. case GDScriptTokenizer::Token::BREAK:
  1445. advance();
  1446. result = parse_break();
  1447. break;
  1448. case GDScriptTokenizer::Token::CONTINUE:
  1449. advance();
  1450. result = parse_continue();
  1451. break;
  1452. case GDScriptTokenizer::Token::RETURN: {
  1453. advance();
  1454. ReturnNode *n_return = alloc_node<ReturnNode>();
  1455. if (!is_statement_end()) {
  1456. if (current_function && (current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._init || current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._static_init)) {
  1457. push_error(R"(Constructor cannot return a value.)");
  1458. }
  1459. n_return->return_value = parse_expression(false);
  1460. } else if (in_lambda && !is_statement_end_token()) {
  1461. // Try to parse it anyway as this might not be the statement end in a lambda.
  1462. // If this fails the expression will be nullptr, but that's the same as no return, so it's fine.
  1463. n_return->return_value = parse_expression(false);
  1464. }
  1465. complete_extents(n_return);
  1466. result = n_return;
  1467. current_suite->has_return = true;
  1468. end_statement("return statement");
  1469. break;
  1470. }
  1471. case GDScriptTokenizer::Token::BREAKPOINT:
  1472. advance();
  1473. result = alloc_node<BreakpointNode>();
  1474. complete_extents(result);
  1475. end_statement(R"("breakpoint")");
  1476. break;
  1477. case GDScriptTokenizer::Token::ASSERT:
  1478. advance();
  1479. result = parse_assert();
  1480. break;
  1481. case GDScriptTokenizer::Token::ANNOTATION: {
  1482. advance();
  1483. is_annotation = true;
  1484. AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT);
  1485. if (annotation != nullptr) {
  1486. annotation_stack.push_back(annotation);
  1487. }
  1488. break;
  1489. }
  1490. default: {
  1491. // Expression statement.
  1492. ExpressionNode *expression = parse_expression(true); // Allow assignment here.
  1493. bool has_ended_lambda = false;
  1494. if (expression == nullptr) {
  1495. if (in_lambda) {
  1496. // If it's not a valid expression beginning, it might be the continuation of the outer expression where this lambda is.
  1497. lambda_ended = true;
  1498. has_ended_lambda = true;
  1499. } else {
  1500. advance();
  1501. push_error(vformat(R"(Expected statement, found "%s" instead.)", previous.get_name()));
  1502. }
  1503. } else {
  1504. end_statement("expression");
  1505. }
  1506. lambda_ended = lambda_ended || has_ended_lambda;
  1507. result = expression;
  1508. #ifdef DEBUG_ENABLED
  1509. if (expression != nullptr) {
  1510. switch (expression->type) {
  1511. case Node::CALL:
  1512. case Node::ASSIGNMENT:
  1513. case Node::AWAIT:
  1514. case Node::TERNARY_OPERATOR:
  1515. // Fine.
  1516. break;
  1517. case Node::LAMBDA:
  1518. // Standalone lambdas can't be used, so make this an error.
  1519. push_error("Standalone lambdas cannot be accessed. Consider assigning it to a variable.", expression);
  1520. break;
  1521. case Node::LITERAL:
  1522. if (static_cast<GDScriptParser::LiteralNode *>(expression)->value.get_type() == Variant::STRING) {
  1523. // Allow strings as multiline comments.
  1524. break;
  1525. }
  1526. [[fallthrough]];
  1527. default:
  1528. push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
  1529. }
  1530. }
  1531. #endif
  1532. break;
  1533. }
  1534. }
  1535. while (!is_annotation && result != nullptr && !annotation_stack.is_empty()) {
  1536. AnnotationNode *last_annotation = annotation_stack.back()->get();
  1537. if (last_annotation->applies_to(AnnotationInfo::STATEMENT)) {
  1538. result->annotations.push_front(last_annotation);
  1539. annotation_stack.pop_back();
  1540. } else {
  1541. push_error(vformat(R"(Annotation "%s" cannot be applied to a statement.)", last_annotation->name));
  1542. clear_unused_annotations();
  1543. }
  1544. }
  1545. #ifdef DEBUG_ENABLED
  1546. if (unreachable && result != nullptr) {
  1547. current_suite->has_unreachable_code = true;
  1548. if (current_function) {
  1549. push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier ? current_function->identifier->name : "<anonymous lambda>");
  1550. } else {
  1551. // TODO: Properties setters and getters with unreachable code are not being warned
  1552. }
  1553. }
  1554. #endif
  1555. if (panic_mode) {
  1556. synchronize();
  1557. }
  1558. return result;
  1559. }
  1560. GDScriptParser::AssertNode *GDScriptParser::parse_assert() {
  1561. // TODO: Add assert message.
  1562. AssertNode *assert = alloc_node<AssertNode>();
  1563. push_multiline(true);
  1564. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "assert".)");
  1565. assert->condition = parse_expression(false);
  1566. if (assert->condition == nullptr) {
  1567. push_error("Expected expression to assert.");
  1568. pop_multiline();
  1569. complete_extents(assert);
  1570. return nullptr;
  1571. }
  1572. if (match(GDScriptTokenizer::Token::COMMA) && !check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1573. assert->message = parse_expression(false);
  1574. if (assert->message == nullptr) {
  1575. push_error(R"(Expected error message for assert after ",".)");
  1576. pop_multiline();
  1577. complete_extents(assert);
  1578. return nullptr;
  1579. }
  1580. match(GDScriptTokenizer::Token::COMMA);
  1581. }
  1582. pop_multiline();
  1583. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after assert expression.)*");
  1584. complete_extents(assert);
  1585. end_statement(R"("assert")");
  1586. return assert;
  1587. }
  1588. GDScriptParser::BreakNode *GDScriptParser::parse_break() {
  1589. if (!can_break) {
  1590. push_error(R"(Cannot use "break" outside of a loop.)");
  1591. }
  1592. BreakNode *break_node = alloc_node<BreakNode>();
  1593. complete_extents(break_node);
  1594. end_statement(R"("break")");
  1595. return break_node;
  1596. }
  1597. GDScriptParser::ContinueNode *GDScriptParser::parse_continue() {
  1598. if (!can_continue) {
  1599. push_error(R"(Cannot use "continue" outside of a loop.)");
  1600. }
  1601. current_suite->has_continue = true;
  1602. ContinueNode *cont = alloc_node<ContinueNode>();
  1603. complete_extents(cont);
  1604. end_statement(R"("continue")");
  1605. return cont;
  1606. }
  1607. GDScriptParser::ForNode *GDScriptParser::parse_for() {
  1608. ForNode *n_for = alloc_node<ForNode>();
  1609. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected loop variable name after "for".)")) {
  1610. n_for->variable = parse_identifier();
  1611. }
  1612. consume(GDScriptTokenizer::Token::IN, R"(Expected "in" after "for" variable name.)");
  1613. n_for->list = parse_expression(false);
  1614. if (!n_for->list) {
  1615. push_error(R"(Expected iterable after "in".)");
  1616. }
  1617. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "for" condition.)");
  1618. // Save break/continue state.
  1619. bool could_break = can_break;
  1620. bool could_continue = can_continue;
  1621. // Allow break/continue.
  1622. can_break = true;
  1623. can_continue = true;
  1624. SuiteNode *suite = alloc_node<SuiteNode>();
  1625. if (n_for->variable) {
  1626. const SuiteNode::Local &local = current_suite->get_local(n_for->variable->name);
  1627. if (local.type != SuiteNode::Local::UNDEFINED) {
  1628. 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);
  1629. }
  1630. suite->add_local(SuiteNode::Local(n_for->variable, current_function));
  1631. }
  1632. n_for->loop = parse_suite(R"("for" block)", suite);
  1633. n_for->loop->is_loop = true;
  1634. complete_extents(n_for);
  1635. // Reset break/continue state.
  1636. can_break = could_break;
  1637. can_continue = could_continue;
  1638. return n_for;
  1639. }
  1640. GDScriptParser::IfNode *GDScriptParser::parse_if(const String &p_token) {
  1641. IfNode *n_if = alloc_node<IfNode>();
  1642. n_if->condition = parse_expression(false);
  1643. if (n_if->condition == nullptr) {
  1644. push_error(vformat(R"(Expected conditional expression after "%s".)", p_token));
  1645. }
  1646. consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after "%s" condition.)", p_token));
  1647. n_if->true_block = parse_suite(vformat(R"("%s" block)", p_token));
  1648. n_if->true_block->parent_if = n_if;
  1649. if (n_if->true_block->has_continue) {
  1650. current_suite->has_continue = true;
  1651. }
  1652. if (match(GDScriptTokenizer::Token::ELIF)) {
  1653. SuiteNode *else_block = alloc_node<SuiteNode>();
  1654. else_block->parent_function = current_function;
  1655. else_block->parent_block = current_suite;
  1656. SuiteNode *previous_suite = current_suite;
  1657. current_suite = else_block;
  1658. IfNode *elif = parse_if("elif");
  1659. else_block->statements.push_back(elif);
  1660. complete_extents(else_block);
  1661. n_if->false_block = else_block;
  1662. current_suite = previous_suite;
  1663. } else if (match(GDScriptTokenizer::Token::ELSE)) {
  1664. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "else".)");
  1665. n_if->false_block = parse_suite(R"("else" block)");
  1666. }
  1667. complete_extents(n_if);
  1668. if (n_if->false_block != nullptr && n_if->false_block->has_return && n_if->true_block->has_return) {
  1669. current_suite->has_return = true;
  1670. }
  1671. if (n_if->false_block != nullptr && n_if->false_block->has_continue) {
  1672. current_suite->has_continue = true;
  1673. }
  1674. return n_if;
  1675. }
  1676. GDScriptParser::MatchNode *GDScriptParser::parse_match() {
  1677. MatchNode *match = alloc_node<MatchNode>();
  1678. match->test = parse_expression(false);
  1679. if (match->test == nullptr) {
  1680. push_error(R"(Expected expression to test after "match".)");
  1681. }
  1682. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" expression.)");
  1683. consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected a newline after "match" statement.)");
  1684. if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected an indented block after "match" statement.)")) {
  1685. complete_extents(match);
  1686. return match;
  1687. }
  1688. bool all_have_return = true;
  1689. bool have_wildcard = false;
  1690. while (!check(GDScriptTokenizer::Token::DEDENT) && !is_at_end()) {
  1691. MatchBranchNode *branch = parse_match_branch();
  1692. if (branch == nullptr) {
  1693. advance();
  1694. continue;
  1695. }
  1696. #ifdef DEBUG_ENABLED
  1697. if (have_wildcard && !branch->patterns.is_empty()) {
  1698. push_warning(branch->patterns[0], GDScriptWarning::UNREACHABLE_PATTERN);
  1699. }
  1700. #endif
  1701. have_wildcard = have_wildcard || branch->has_wildcard;
  1702. all_have_return = all_have_return && branch->block->has_return;
  1703. match->branches.push_back(branch);
  1704. }
  1705. complete_extents(match);
  1706. consume(GDScriptTokenizer::Token::DEDENT, R"(Expected an indented block after "match" statement.)");
  1707. if (all_have_return && have_wildcard) {
  1708. current_suite->has_return = true;
  1709. }
  1710. return match;
  1711. }
  1712. GDScriptParser::MatchBranchNode *GDScriptParser::parse_match_branch() {
  1713. MatchBranchNode *branch = alloc_node<MatchBranchNode>();
  1714. reset_extents(branch, current);
  1715. bool has_bind = false;
  1716. do {
  1717. PatternNode *pattern = parse_match_pattern();
  1718. if (pattern == nullptr) {
  1719. continue;
  1720. }
  1721. if (pattern->binds.size() > 0) {
  1722. has_bind = true;
  1723. }
  1724. if (branch->patterns.size() > 0 && has_bind) {
  1725. push_error(R"(Cannot use a variable bind with multiple patterns.)");
  1726. }
  1727. if (pattern->pattern_type == PatternNode::PT_REST) {
  1728. push_error(R"(Rest pattern can only be used inside array and dictionary patterns.)");
  1729. } else if (pattern->pattern_type == PatternNode::PT_BIND || pattern->pattern_type == PatternNode::PT_WILDCARD) {
  1730. branch->has_wildcard = true;
  1731. }
  1732. branch->patterns.push_back(pattern);
  1733. } while (match(GDScriptTokenizer::Token::COMMA));
  1734. if (branch->patterns.is_empty()) {
  1735. push_error(R"(No pattern found for "match" branch.)");
  1736. }
  1737. if (!consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" patterns.)")) {
  1738. complete_extents(branch);
  1739. return nullptr;
  1740. }
  1741. SuiteNode *suite = alloc_node<SuiteNode>();
  1742. if (branch->patterns.size() > 0) {
  1743. for (const KeyValue<StringName, IdentifierNode *> &E : branch->patterns[0]->binds) {
  1744. SuiteNode::Local local(E.value, current_function);
  1745. local.type = SuiteNode::Local::PATTERN_BIND;
  1746. suite->add_local(local);
  1747. }
  1748. }
  1749. branch->block = parse_suite("match pattern block", suite);
  1750. complete_extents(branch);
  1751. return branch;
  1752. }
  1753. GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_root_pattern) {
  1754. PatternNode *pattern = alloc_node<PatternNode>();
  1755. reset_extents(pattern, current);
  1756. switch (current.type) {
  1757. case GDScriptTokenizer::Token::VAR: {
  1758. // Bind.
  1759. advance();
  1760. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected bind name after "var".)")) {
  1761. complete_extents(pattern);
  1762. return nullptr;
  1763. }
  1764. pattern->pattern_type = PatternNode::PT_BIND;
  1765. pattern->bind = parse_identifier();
  1766. PatternNode *root_pattern = p_root_pattern == nullptr ? pattern : p_root_pattern;
  1767. if (p_root_pattern != nullptr) {
  1768. if (p_root_pattern->has_bind(pattern->bind->name)) {
  1769. push_error(vformat(R"(Bind variable name "%s" was already used in this pattern.)", pattern->bind->name));
  1770. complete_extents(pattern);
  1771. return nullptr;
  1772. }
  1773. }
  1774. if (current_suite->has_local(pattern->bind->name)) {
  1775. 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));
  1776. complete_extents(pattern);
  1777. return nullptr;
  1778. }
  1779. root_pattern->binds[pattern->bind->name] = pattern->bind;
  1780. } break;
  1781. case GDScriptTokenizer::Token::UNDERSCORE:
  1782. // Wildcard.
  1783. advance();
  1784. pattern->pattern_type = PatternNode::PT_WILDCARD;
  1785. break;
  1786. case GDScriptTokenizer::Token::PERIOD_PERIOD:
  1787. // Rest.
  1788. advance();
  1789. pattern->pattern_type = PatternNode::PT_REST;
  1790. break;
  1791. case GDScriptTokenizer::Token::BRACKET_OPEN: {
  1792. // Array.
  1793. advance();
  1794. pattern->pattern_type = PatternNode::PT_ARRAY;
  1795. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  1796. do {
  1797. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  1798. if (sub_pattern == nullptr) {
  1799. continue;
  1800. }
  1801. if (pattern->rest_used) {
  1802. push_error(R"(The ".." pattern must be the last element in the pattern array.)");
  1803. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  1804. pattern->rest_used = true;
  1805. }
  1806. pattern->array.push_back(sub_pattern);
  1807. } while (match(GDScriptTokenizer::Token::COMMA));
  1808. }
  1809. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" to close the array pattern.)");
  1810. break;
  1811. }
  1812. case GDScriptTokenizer::Token::BRACE_OPEN: {
  1813. // Dictionary.
  1814. advance();
  1815. pattern->pattern_type = PatternNode::PT_DICTIONARY;
  1816. do {
  1817. if (check(GDScriptTokenizer::Token::BRACE_CLOSE) || is_at_end()) {
  1818. break;
  1819. }
  1820. if (match(GDScriptTokenizer::Token::PERIOD_PERIOD)) {
  1821. // Rest.
  1822. if (pattern->rest_used) {
  1823. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  1824. } else {
  1825. PatternNode *sub_pattern = alloc_node<PatternNode>();
  1826. complete_extents(sub_pattern);
  1827. sub_pattern->pattern_type = PatternNode::PT_REST;
  1828. pattern->dictionary.push_back({ nullptr, sub_pattern });
  1829. pattern->rest_used = true;
  1830. }
  1831. } else {
  1832. ExpressionNode *key = parse_expression(false);
  1833. if (key == nullptr) {
  1834. push_error(R"(Expected expression as key for dictionary pattern.)");
  1835. }
  1836. if (match(GDScriptTokenizer::Token::COLON)) {
  1837. // Value pattern.
  1838. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  1839. if (sub_pattern == nullptr) {
  1840. continue;
  1841. }
  1842. if (pattern->rest_used) {
  1843. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  1844. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  1845. push_error(R"(The ".." pattern cannot be used as a value.)");
  1846. } else {
  1847. pattern->dictionary.push_back({ key, sub_pattern });
  1848. }
  1849. } else {
  1850. // Key match only.
  1851. pattern->dictionary.push_back({ key, nullptr });
  1852. }
  1853. }
  1854. } while (match(GDScriptTokenizer::Token::COMMA));
  1855. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected "}" to close the dictionary pattern.)");
  1856. break;
  1857. }
  1858. default: {
  1859. // Expression.
  1860. ExpressionNode *expression = parse_expression(false);
  1861. if (expression == nullptr) {
  1862. push_error(R"(Expected expression for match pattern.)");
  1863. return nullptr;
  1864. } else {
  1865. if (expression->type == GDScriptParser::Node::LITERAL) {
  1866. pattern->pattern_type = PatternNode::PT_LITERAL;
  1867. } else {
  1868. pattern->pattern_type = PatternNode::PT_EXPRESSION;
  1869. }
  1870. pattern->expression = expression;
  1871. }
  1872. break;
  1873. }
  1874. }
  1875. complete_extents(pattern);
  1876. return pattern;
  1877. }
  1878. bool GDScriptParser::PatternNode::has_bind(const StringName &p_name) {
  1879. return binds.has(p_name);
  1880. }
  1881. GDScriptParser::IdentifierNode *GDScriptParser::PatternNode::get_bind(const StringName &p_name) {
  1882. return binds[p_name];
  1883. }
  1884. GDScriptParser::WhileNode *GDScriptParser::parse_while() {
  1885. WhileNode *n_while = alloc_node<WhileNode>();
  1886. n_while->condition = parse_expression(false);
  1887. if (n_while->condition == nullptr) {
  1888. push_error(R"(Expected conditional expression after "while".)");
  1889. }
  1890. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "while" condition.)");
  1891. // Save break/continue state.
  1892. bool could_break = can_break;
  1893. bool could_continue = can_continue;
  1894. // Allow break/continue.
  1895. can_break = true;
  1896. can_continue = true;
  1897. n_while->loop = parse_suite(R"("while" block)");
  1898. n_while->loop->is_loop = true;
  1899. complete_extents(n_while);
  1900. // Reset break/continue state.
  1901. can_break = could_break;
  1902. can_continue = could_continue;
  1903. return n_while;
  1904. }
  1905. GDScriptParser::ExpressionNode *GDScriptParser::parse_precedence(Precedence p_precedence, bool p_can_assign, bool p_stop_on_assign) {
  1906. // Switch multiline mode on for grouping tokens.
  1907. // Do this early to avoid the tokenizer generating whitespace tokens.
  1908. switch (current.type) {
  1909. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  1910. case GDScriptTokenizer::Token::BRACE_OPEN:
  1911. case GDScriptTokenizer::Token::BRACKET_OPEN:
  1912. push_multiline(true);
  1913. break;
  1914. default:
  1915. break; // Nothing to do.
  1916. }
  1917. // Completion can appear whenever an expression is expected.
  1918. make_completion_context(COMPLETION_IDENTIFIER, nullptr);
  1919. GDScriptTokenizer::Token token = current;
  1920. GDScriptTokenizer::Token::Type token_type = token.type;
  1921. if (token.is_identifier()) {
  1922. // Allow keywords that can be treated as identifiers.
  1923. token_type = GDScriptTokenizer::Token::IDENTIFIER;
  1924. }
  1925. ParseFunction prefix_rule = get_rule(token_type)->prefix;
  1926. if (prefix_rule == nullptr) {
  1927. // Expected expression. Let the caller give the proper error message.
  1928. return nullptr;
  1929. }
  1930. advance(); // Only consume the token if there's a valid rule.
  1931. ExpressionNode *previous_operand = (this->*prefix_rule)(nullptr, p_can_assign);
  1932. while (p_precedence <= get_rule(current.type)->precedence) {
  1933. if (previous_operand == nullptr || (p_stop_on_assign && current.type == GDScriptTokenizer::Token::EQUAL) || (previous_operand->type == Node::LAMBDA && lambda_ended)) {
  1934. return previous_operand;
  1935. }
  1936. // Also switch multiline mode on here for infix operators.
  1937. switch (current.type) {
  1938. // case GDScriptTokenizer::Token::BRACE_OPEN: // Not an infix operator.
  1939. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  1940. case GDScriptTokenizer::Token::BRACKET_OPEN:
  1941. push_multiline(true);
  1942. break;
  1943. default:
  1944. break; // Nothing to do.
  1945. }
  1946. token = advance();
  1947. ParseFunction infix_rule = get_rule(token.type)->infix;
  1948. previous_operand = (this->*infix_rule)(previous_operand, p_can_assign);
  1949. }
  1950. return previous_operand;
  1951. }
  1952. GDScriptParser::ExpressionNode *GDScriptParser::parse_expression(bool p_can_assign, bool p_stop_on_assign) {
  1953. return parse_precedence(PREC_ASSIGNMENT, p_can_assign, p_stop_on_assign);
  1954. }
  1955. GDScriptParser::IdentifierNode *GDScriptParser::parse_identifier() {
  1956. IdentifierNode *identifier = static_cast<IdentifierNode *>(parse_identifier(nullptr, false));
  1957. #ifdef DEBUG_ENABLED
  1958. // Check for spoofing here (if available in TextServer) since this isn't called inside expressions. This is only relevant for declarations.
  1959. if (identifier && TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier->name.operator String())) {
  1960. push_warning(identifier, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier->name.operator String());
  1961. }
  1962. #endif
  1963. return identifier;
  1964. }
  1965. GDScriptParser::ExpressionNode *GDScriptParser::parse_identifier(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1966. if (!previous.is_identifier()) {
  1967. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing identifier node without identifier token.");
  1968. }
  1969. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  1970. complete_extents(identifier);
  1971. identifier->name = previous.get_identifier();
  1972. if (current_suite != nullptr && current_suite->has_local(identifier->name)) {
  1973. const SuiteNode::Local &declaration = current_suite->get_local(identifier->name);
  1974. identifier->source_function = declaration.source_function;
  1975. switch (declaration.type) {
  1976. case SuiteNode::Local::CONSTANT:
  1977. identifier->source = IdentifierNode::LOCAL_CONSTANT;
  1978. identifier->constant_source = declaration.constant;
  1979. declaration.constant->usages++;
  1980. break;
  1981. case SuiteNode::Local::VARIABLE:
  1982. identifier->source = IdentifierNode::LOCAL_VARIABLE;
  1983. identifier->variable_source = declaration.variable;
  1984. declaration.variable->usages++;
  1985. break;
  1986. case SuiteNode::Local::PARAMETER:
  1987. identifier->source = IdentifierNode::FUNCTION_PARAMETER;
  1988. identifier->parameter_source = declaration.parameter;
  1989. declaration.parameter->usages++;
  1990. break;
  1991. case SuiteNode::Local::FOR_VARIABLE:
  1992. identifier->source = IdentifierNode::LOCAL_ITERATOR;
  1993. identifier->bind_source = declaration.bind;
  1994. declaration.bind->usages++;
  1995. break;
  1996. case SuiteNode::Local::PATTERN_BIND:
  1997. identifier->source = IdentifierNode::LOCAL_BIND;
  1998. identifier->bind_source = declaration.bind;
  1999. declaration.bind->usages++;
  2000. break;
  2001. case SuiteNode::Local::UNDEFINED:
  2002. ERR_FAIL_V_MSG(nullptr, "Undefined local found.");
  2003. }
  2004. }
  2005. return identifier;
  2006. }
  2007. GDScriptParser::LiteralNode *GDScriptParser::parse_literal() {
  2008. return static_cast<LiteralNode *>(parse_literal(nullptr, false));
  2009. }
  2010. GDScriptParser::ExpressionNode *GDScriptParser::parse_literal(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2011. if (previous.type != GDScriptTokenizer::Token::LITERAL) {
  2012. push_error("Parser bug: parsing literal node without literal token.");
  2013. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing literal node without literal token.");
  2014. }
  2015. LiteralNode *literal = alloc_node<LiteralNode>();
  2016. complete_extents(literal);
  2017. literal->value = previous.literal;
  2018. return literal;
  2019. }
  2020. GDScriptParser::ExpressionNode *GDScriptParser::parse_self(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2021. if (current_function && current_function->is_static) {
  2022. push_error(R"(Cannot use "self" inside a static function.)");
  2023. }
  2024. SelfNode *self = alloc_node<SelfNode>();
  2025. complete_extents(self);
  2026. self->current_class = current_class;
  2027. return self;
  2028. }
  2029. GDScriptParser::ExpressionNode *GDScriptParser::parse_builtin_constant(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2030. GDScriptTokenizer::Token::Type op_type = previous.type;
  2031. LiteralNode *constant = alloc_node<LiteralNode>();
  2032. complete_extents(constant);
  2033. switch (op_type) {
  2034. case GDScriptTokenizer::Token::CONST_PI:
  2035. constant->value = Math_PI;
  2036. break;
  2037. case GDScriptTokenizer::Token::CONST_TAU:
  2038. constant->value = Math_TAU;
  2039. break;
  2040. case GDScriptTokenizer::Token::CONST_INF:
  2041. constant->value = INFINITY;
  2042. break;
  2043. case GDScriptTokenizer::Token::CONST_NAN:
  2044. constant->value = NAN;
  2045. break;
  2046. default:
  2047. return nullptr; // Unreachable.
  2048. }
  2049. return constant;
  2050. }
  2051. GDScriptParser::ExpressionNode *GDScriptParser::parse_unary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2052. GDScriptTokenizer::Token::Type op_type = previous.type;
  2053. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  2054. switch (op_type) {
  2055. case GDScriptTokenizer::Token::MINUS:
  2056. operation->operation = UnaryOpNode::OP_NEGATIVE;
  2057. operation->variant_op = Variant::OP_NEGATE;
  2058. operation->operand = parse_precedence(PREC_SIGN, false);
  2059. if (operation->operand == nullptr) {
  2060. push_error(R"(Expected expression after "-" operator.)");
  2061. }
  2062. break;
  2063. case GDScriptTokenizer::Token::PLUS:
  2064. operation->operation = UnaryOpNode::OP_POSITIVE;
  2065. operation->variant_op = Variant::OP_POSITIVE;
  2066. operation->operand = parse_precedence(PREC_SIGN, false);
  2067. if (operation->operand == nullptr) {
  2068. push_error(R"(Expected expression after "+" operator.)");
  2069. }
  2070. break;
  2071. case GDScriptTokenizer::Token::TILDE:
  2072. operation->operation = UnaryOpNode::OP_COMPLEMENT;
  2073. operation->variant_op = Variant::OP_BIT_NEGATE;
  2074. operation->operand = parse_precedence(PREC_BIT_NOT, false);
  2075. if (operation->operand == nullptr) {
  2076. push_error(R"(Expected expression after "~" operator.)");
  2077. }
  2078. break;
  2079. case GDScriptTokenizer::Token::NOT:
  2080. case GDScriptTokenizer::Token::BANG:
  2081. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  2082. operation->variant_op = Variant::OP_NOT;
  2083. operation->operand = parse_precedence(PREC_LOGIC_NOT, false);
  2084. if (operation->operand == nullptr) {
  2085. push_error(vformat(R"(Expected expression after "%s" operator.)", op_type == GDScriptTokenizer::Token::NOT ? "not" : "!"));
  2086. }
  2087. break;
  2088. default:
  2089. complete_extents(operation);
  2090. return nullptr; // Unreachable.
  2091. }
  2092. complete_extents(operation);
  2093. return operation;
  2094. }
  2095. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_not_in_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2096. // check that NOT is followed by IN by consuming it before calling parse_binary_operator which will only receive a plain IN
  2097. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  2098. reset_extents(operation, p_previous_operand);
  2099. update_extents(operation);
  2100. consume(GDScriptTokenizer::Token::IN, R"(Expected "in" after "not" in content-test operator.)");
  2101. ExpressionNode *in_operation = parse_binary_operator(p_previous_operand, p_can_assign);
  2102. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  2103. operation->variant_op = Variant::OP_NOT;
  2104. operation->operand = in_operation;
  2105. complete_extents(operation);
  2106. return operation;
  2107. }
  2108. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2109. GDScriptTokenizer::Token op = previous;
  2110. BinaryOpNode *operation = alloc_node<BinaryOpNode>();
  2111. reset_extents(operation, p_previous_operand);
  2112. update_extents(operation);
  2113. Precedence precedence = (Precedence)(get_rule(op.type)->precedence + 1);
  2114. operation->left_operand = p_previous_operand;
  2115. operation->right_operand = parse_precedence(precedence, false);
  2116. complete_extents(operation);
  2117. if (operation->right_operand == nullptr) {
  2118. push_error(vformat(R"(Expected expression after "%s" operator.")", op.get_name()));
  2119. }
  2120. // TODO: Also for unary, ternary, and assignment.
  2121. switch (op.type) {
  2122. case GDScriptTokenizer::Token::PLUS:
  2123. operation->operation = BinaryOpNode::OP_ADDITION;
  2124. operation->variant_op = Variant::OP_ADD;
  2125. break;
  2126. case GDScriptTokenizer::Token::MINUS:
  2127. operation->operation = BinaryOpNode::OP_SUBTRACTION;
  2128. operation->variant_op = Variant::OP_SUBTRACT;
  2129. break;
  2130. case GDScriptTokenizer::Token::STAR:
  2131. operation->operation = BinaryOpNode::OP_MULTIPLICATION;
  2132. operation->variant_op = Variant::OP_MULTIPLY;
  2133. break;
  2134. case GDScriptTokenizer::Token::SLASH:
  2135. operation->operation = BinaryOpNode::OP_DIVISION;
  2136. operation->variant_op = Variant::OP_DIVIDE;
  2137. break;
  2138. case GDScriptTokenizer::Token::PERCENT:
  2139. operation->operation = BinaryOpNode::OP_MODULO;
  2140. operation->variant_op = Variant::OP_MODULE;
  2141. break;
  2142. case GDScriptTokenizer::Token::STAR_STAR:
  2143. operation->operation = BinaryOpNode::OP_POWER;
  2144. operation->variant_op = Variant::OP_POWER;
  2145. break;
  2146. case GDScriptTokenizer::Token::LESS_LESS:
  2147. operation->operation = BinaryOpNode::OP_BIT_LEFT_SHIFT;
  2148. operation->variant_op = Variant::OP_SHIFT_LEFT;
  2149. break;
  2150. case GDScriptTokenizer::Token::GREATER_GREATER:
  2151. operation->operation = BinaryOpNode::OP_BIT_RIGHT_SHIFT;
  2152. operation->variant_op = Variant::OP_SHIFT_RIGHT;
  2153. break;
  2154. case GDScriptTokenizer::Token::AMPERSAND:
  2155. operation->operation = BinaryOpNode::OP_BIT_AND;
  2156. operation->variant_op = Variant::OP_BIT_AND;
  2157. break;
  2158. case GDScriptTokenizer::Token::PIPE:
  2159. operation->operation = BinaryOpNode::OP_BIT_OR;
  2160. operation->variant_op = Variant::OP_BIT_OR;
  2161. break;
  2162. case GDScriptTokenizer::Token::CARET:
  2163. operation->operation = BinaryOpNode::OP_BIT_XOR;
  2164. operation->variant_op = Variant::OP_BIT_XOR;
  2165. break;
  2166. case GDScriptTokenizer::Token::AND:
  2167. case GDScriptTokenizer::Token::AMPERSAND_AMPERSAND:
  2168. operation->operation = BinaryOpNode::OP_LOGIC_AND;
  2169. operation->variant_op = Variant::OP_AND;
  2170. break;
  2171. case GDScriptTokenizer::Token::OR:
  2172. case GDScriptTokenizer::Token::PIPE_PIPE:
  2173. operation->operation = BinaryOpNode::OP_LOGIC_OR;
  2174. operation->variant_op = Variant::OP_OR;
  2175. break;
  2176. case GDScriptTokenizer::Token::IN:
  2177. operation->operation = BinaryOpNode::OP_CONTENT_TEST;
  2178. operation->variant_op = Variant::OP_IN;
  2179. break;
  2180. case GDScriptTokenizer::Token::EQUAL_EQUAL:
  2181. operation->operation = BinaryOpNode::OP_COMP_EQUAL;
  2182. operation->variant_op = Variant::OP_EQUAL;
  2183. break;
  2184. case GDScriptTokenizer::Token::BANG_EQUAL:
  2185. operation->operation = BinaryOpNode::OP_COMP_NOT_EQUAL;
  2186. operation->variant_op = Variant::OP_NOT_EQUAL;
  2187. break;
  2188. case GDScriptTokenizer::Token::LESS:
  2189. operation->operation = BinaryOpNode::OP_COMP_LESS;
  2190. operation->variant_op = Variant::OP_LESS;
  2191. break;
  2192. case GDScriptTokenizer::Token::LESS_EQUAL:
  2193. operation->operation = BinaryOpNode::OP_COMP_LESS_EQUAL;
  2194. operation->variant_op = Variant::OP_LESS_EQUAL;
  2195. break;
  2196. case GDScriptTokenizer::Token::GREATER:
  2197. operation->operation = BinaryOpNode::OP_COMP_GREATER;
  2198. operation->variant_op = Variant::OP_GREATER;
  2199. break;
  2200. case GDScriptTokenizer::Token::GREATER_EQUAL:
  2201. operation->operation = BinaryOpNode::OP_COMP_GREATER_EQUAL;
  2202. operation->variant_op = Variant::OP_GREATER_EQUAL;
  2203. break;
  2204. default:
  2205. return nullptr; // Unreachable.
  2206. }
  2207. return operation;
  2208. }
  2209. GDScriptParser::ExpressionNode *GDScriptParser::parse_ternary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2210. // Only one ternary operation exists, so no abstraction here.
  2211. TernaryOpNode *operation = alloc_node<TernaryOpNode>();
  2212. reset_extents(operation, p_previous_operand);
  2213. update_extents(operation);
  2214. operation->true_expr = p_previous_operand;
  2215. operation->condition = parse_precedence(PREC_TERNARY, false);
  2216. if (operation->condition == nullptr) {
  2217. push_error(R"(Expected expression as ternary condition after "if".)");
  2218. }
  2219. consume(GDScriptTokenizer::Token::ELSE, R"(Expected "else" after ternary operator condition.)");
  2220. operation->false_expr = parse_precedence(PREC_TERNARY, false);
  2221. if (operation->false_expr == nullptr) {
  2222. push_error(R"(Expected expression after "else".)");
  2223. }
  2224. complete_extents(operation);
  2225. return operation;
  2226. }
  2227. GDScriptParser::ExpressionNode *GDScriptParser::parse_assignment(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2228. if (!p_can_assign) {
  2229. push_error("Assignment is not allowed inside an expression.");
  2230. return parse_expression(false); // Return the following expression.
  2231. }
  2232. if (p_previous_operand == nullptr) {
  2233. return parse_expression(false); // Return the following expression.
  2234. }
  2235. #ifdef DEBUG_ENABLED
  2236. VariableNode *source_variable = nullptr;
  2237. #endif
  2238. switch (p_previous_operand->type) {
  2239. case Node::IDENTIFIER: {
  2240. #ifdef DEBUG_ENABLED
  2241. // Get source to store assignment count.
  2242. // Also remove one usage since assignment isn't usage.
  2243. IdentifierNode *id = static_cast<IdentifierNode *>(p_previous_operand);
  2244. switch (id->source) {
  2245. case IdentifierNode::LOCAL_VARIABLE:
  2246. source_variable = id->variable_source;
  2247. id->variable_source->usages--;
  2248. break;
  2249. case IdentifierNode::LOCAL_CONSTANT:
  2250. id->constant_source->usages--;
  2251. break;
  2252. case IdentifierNode::FUNCTION_PARAMETER:
  2253. id->parameter_source->usages--;
  2254. break;
  2255. case IdentifierNode::LOCAL_ITERATOR:
  2256. case IdentifierNode::LOCAL_BIND:
  2257. id->bind_source->usages--;
  2258. break;
  2259. default:
  2260. break;
  2261. }
  2262. #endif
  2263. } break;
  2264. case Node::SUBSCRIPT:
  2265. // Okay.
  2266. break;
  2267. default:
  2268. push_error(R"(Only identifier, attribute access, and subscription access can be used as assignment target.)");
  2269. return parse_expression(false); // Return the following expression.
  2270. }
  2271. AssignmentNode *assignment = alloc_node<AssignmentNode>();
  2272. reset_extents(assignment, p_previous_operand);
  2273. update_extents(assignment);
  2274. make_completion_context(COMPLETION_ASSIGN, assignment);
  2275. #ifdef DEBUG_ENABLED
  2276. bool has_operator = true;
  2277. #endif
  2278. switch (previous.type) {
  2279. case GDScriptTokenizer::Token::EQUAL:
  2280. assignment->operation = AssignmentNode::OP_NONE;
  2281. assignment->variant_op = Variant::OP_MAX;
  2282. #ifdef DEBUG_ENABLED
  2283. has_operator = false;
  2284. #endif
  2285. break;
  2286. case GDScriptTokenizer::Token::PLUS_EQUAL:
  2287. assignment->operation = AssignmentNode::OP_ADDITION;
  2288. assignment->variant_op = Variant::OP_ADD;
  2289. break;
  2290. case GDScriptTokenizer::Token::MINUS_EQUAL:
  2291. assignment->operation = AssignmentNode::OP_SUBTRACTION;
  2292. assignment->variant_op = Variant::OP_SUBTRACT;
  2293. break;
  2294. case GDScriptTokenizer::Token::STAR_EQUAL:
  2295. assignment->operation = AssignmentNode::OP_MULTIPLICATION;
  2296. assignment->variant_op = Variant::OP_MULTIPLY;
  2297. break;
  2298. case GDScriptTokenizer::Token::STAR_STAR_EQUAL:
  2299. assignment->operation = AssignmentNode::OP_POWER;
  2300. assignment->variant_op = Variant::OP_POWER;
  2301. break;
  2302. case GDScriptTokenizer::Token::SLASH_EQUAL:
  2303. assignment->operation = AssignmentNode::OP_DIVISION;
  2304. assignment->variant_op = Variant::OP_DIVIDE;
  2305. break;
  2306. case GDScriptTokenizer::Token::PERCENT_EQUAL:
  2307. assignment->operation = AssignmentNode::OP_MODULO;
  2308. assignment->variant_op = Variant::OP_MODULE;
  2309. break;
  2310. case GDScriptTokenizer::Token::LESS_LESS_EQUAL:
  2311. assignment->operation = AssignmentNode::OP_BIT_SHIFT_LEFT;
  2312. assignment->variant_op = Variant::OP_SHIFT_LEFT;
  2313. break;
  2314. case GDScriptTokenizer::Token::GREATER_GREATER_EQUAL:
  2315. assignment->operation = AssignmentNode::OP_BIT_SHIFT_RIGHT;
  2316. assignment->variant_op = Variant::OP_SHIFT_RIGHT;
  2317. break;
  2318. case GDScriptTokenizer::Token::AMPERSAND_EQUAL:
  2319. assignment->operation = AssignmentNode::OP_BIT_AND;
  2320. assignment->variant_op = Variant::OP_BIT_AND;
  2321. break;
  2322. case GDScriptTokenizer::Token::PIPE_EQUAL:
  2323. assignment->operation = AssignmentNode::OP_BIT_OR;
  2324. assignment->variant_op = Variant::OP_BIT_OR;
  2325. break;
  2326. case GDScriptTokenizer::Token::CARET_EQUAL:
  2327. assignment->operation = AssignmentNode::OP_BIT_XOR;
  2328. assignment->variant_op = Variant::OP_BIT_XOR;
  2329. break;
  2330. default:
  2331. break; // Unreachable.
  2332. }
  2333. assignment->assignee = p_previous_operand;
  2334. assignment->assigned_value = parse_expression(false);
  2335. if (assignment->assigned_value == nullptr) {
  2336. push_error(R"(Expected an expression after "=".)");
  2337. }
  2338. complete_extents(assignment);
  2339. #ifdef DEBUG_ENABLED
  2340. if (source_variable != nullptr) {
  2341. if (has_operator && source_variable->assignments == 0) {
  2342. push_warning(assignment, GDScriptWarning::UNASSIGNED_VARIABLE_OP_ASSIGN, source_variable->identifier->name);
  2343. }
  2344. source_variable->assignments += 1;
  2345. }
  2346. #endif
  2347. return assignment;
  2348. }
  2349. GDScriptParser::ExpressionNode *GDScriptParser::parse_await(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2350. AwaitNode *await = alloc_node<AwaitNode>();
  2351. ExpressionNode *element = parse_precedence(PREC_AWAIT, false);
  2352. if (element == nullptr) {
  2353. push_error(R"(Expected signal or coroutine after "await".)");
  2354. }
  2355. await->to_await = element;
  2356. complete_extents(await);
  2357. if (current_function) { // Might be null in a getter or setter.
  2358. current_function->is_coroutine = true;
  2359. }
  2360. return await;
  2361. }
  2362. GDScriptParser::ExpressionNode *GDScriptParser::parse_array(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2363. ArrayNode *array = alloc_node<ArrayNode>();
  2364. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2365. do {
  2366. if (check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2367. // Allow for trailing comma.
  2368. break;
  2369. }
  2370. ExpressionNode *element = parse_expression(false);
  2371. if (element == nullptr) {
  2372. push_error(R"(Expected expression as array element.)");
  2373. } else {
  2374. array->elements.push_back(element);
  2375. }
  2376. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2377. }
  2378. pop_multiline();
  2379. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after array elements.)");
  2380. complete_extents(array);
  2381. return array;
  2382. }
  2383. GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2384. DictionaryNode *dictionary = alloc_node<DictionaryNode>();
  2385. bool decided_style = false;
  2386. if (!check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2387. do {
  2388. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2389. // Allow for trailing comma.
  2390. break;
  2391. }
  2392. // Key.
  2393. ExpressionNode *key = parse_expression(false, true); // Stop on "=" so we can check for Lua table style.
  2394. if (key == nullptr) {
  2395. push_error(R"(Expected expression as dictionary key.)");
  2396. }
  2397. if (!decided_style) {
  2398. switch (current.type) {
  2399. case GDScriptTokenizer::Token::COLON:
  2400. dictionary->style = DictionaryNode::PYTHON_DICT;
  2401. break;
  2402. case GDScriptTokenizer::Token::EQUAL:
  2403. dictionary->style = DictionaryNode::LUA_TABLE;
  2404. break;
  2405. default:
  2406. push_error(R"(Expected ":" or "=" after dictionary key.)");
  2407. break;
  2408. }
  2409. decided_style = true;
  2410. }
  2411. switch (dictionary->style) {
  2412. case DictionaryNode::LUA_TABLE:
  2413. if (key != nullptr && key->type != Node::IDENTIFIER && key->type != Node::LITERAL) {
  2414. push_error("Expected identifier or string as LUA-style dictionary key.");
  2415. advance();
  2416. break;
  2417. }
  2418. if (key != nullptr && key->type == Node::LITERAL && static_cast<LiteralNode *>(key)->value.get_type() != Variant::STRING) {
  2419. push_error("Expected identifier or string as LUA-style dictionary key.");
  2420. advance();
  2421. break;
  2422. }
  2423. if (!match(GDScriptTokenizer::Token::EQUAL)) {
  2424. if (match(GDScriptTokenizer::Token::COLON)) {
  2425. push_error(R"(Expected "=" after dictionary key. Mixing dictionary styles is not allowed.)");
  2426. advance(); // Consume wrong separator anyway.
  2427. } else {
  2428. push_error(R"(Expected "=" after dictionary key.)");
  2429. }
  2430. }
  2431. if (key != nullptr) {
  2432. key->is_constant = true;
  2433. if (key->type == Node::IDENTIFIER) {
  2434. key->reduced_value = static_cast<IdentifierNode *>(key)->name;
  2435. } else if (key->type == Node::LITERAL) {
  2436. key->reduced_value = StringName(static_cast<LiteralNode *>(key)->value.operator String());
  2437. }
  2438. }
  2439. break;
  2440. case DictionaryNode::PYTHON_DICT:
  2441. if (!match(GDScriptTokenizer::Token::COLON)) {
  2442. if (match(GDScriptTokenizer::Token::EQUAL)) {
  2443. push_error(R"(Expected ":" after dictionary key. Mixing dictionary styles is not allowed.)");
  2444. advance(); // Consume wrong separator anyway.
  2445. } else {
  2446. push_error(R"(Expected ":" after dictionary key.)");
  2447. }
  2448. }
  2449. break;
  2450. }
  2451. // Value.
  2452. ExpressionNode *value = parse_expression(false);
  2453. if (value == nullptr) {
  2454. push_error(R"(Expected expression as dictionary value.)");
  2455. }
  2456. if (key != nullptr && value != nullptr) {
  2457. dictionary->elements.push_back({ key, value });
  2458. }
  2459. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2460. }
  2461. pop_multiline();
  2462. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" after dictionary elements.)");
  2463. complete_extents(dictionary);
  2464. return dictionary;
  2465. }
  2466. GDScriptParser::ExpressionNode *GDScriptParser::parse_grouping(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2467. ExpressionNode *grouped = parse_expression(false);
  2468. pop_multiline();
  2469. if (grouped == nullptr) {
  2470. push_error(R"(Expected grouping expression.)");
  2471. } else {
  2472. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after grouping expression.)*");
  2473. }
  2474. return grouped;
  2475. }
  2476. GDScriptParser::ExpressionNode *GDScriptParser::parse_attribute(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2477. SubscriptNode *attribute = alloc_node<SubscriptNode>();
  2478. reset_extents(attribute, p_previous_operand);
  2479. update_extents(attribute);
  2480. if (for_completion) {
  2481. bool is_builtin = false;
  2482. if (p_previous_operand && p_previous_operand->type == Node::IDENTIFIER) {
  2483. const IdentifierNode *id = static_cast<const IdentifierNode *>(p_previous_operand);
  2484. Variant::Type builtin_type = get_builtin_type(id->name);
  2485. if (builtin_type < Variant::VARIANT_MAX) {
  2486. make_completion_context(COMPLETION_BUILT_IN_TYPE_CONSTANT_OR_STATIC_METHOD, builtin_type, true);
  2487. is_builtin = true;
  2488. }
  2489. }
  2490. if (!is_builtin) {
  2491. make_completion_context(COMPLETION_ATTRIBUTE, attribute, -1, true);
  2492. }
  2493. }
  2494. attribute->base = p_previous_operand;
  2495. if (current.is_node_name()) {
  2496. current.type = GDScriptTokenizer::Token::IDENTIFIER;
  2497. }
  2498. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier after "." for attribute access.)")) {
  2499. complete_extents(attribute);
  2500. return attribute;
  2501. }
  2502. attribute->is_attribute = true;
  2503. attribute->attribute = parse_identifier();
  2504. complete_extents(attribute);
  2505. return attribute;
  2506. }
  2507. GDScriptParser::ExpressionNode *GDScriptParser::parse_subscript(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2508. SubscriptNode *subscript = alloc_node<SubscriptNode>();
  2509. reset_extents(subscript, p_previous_operand);
  2510. update_extents(subscript);
  2511. make_completion_context(COMPLETION_SUBSCRIPT, subscript);
  2512. subscript->base = p_previous_operand;
  2513. subscript->index = parse_expression(false);
  2514. if (subscript->index == nullptr) {
  2515. push_error(R"(Expected expression after "[".)");
  2516. }
  2517. pop_multiline();
  2518. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" after subscription index.)");
  2519. complete_extents(subscript);
  2520. return subscript;
  2521. }
  2522. GDScriptParser::ExpressionNode *GDScriptParser::parse_cast(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2523. CastNode *cast = alloc_node<CastNode>();
  2524. reset_extents(cast, p_previous_operand);
  2525. update_extents(cast);
  2526. cast->operand = p_previous_operand;
  2527. cast->cast_type = parse_type();
  2528. complete_extents(cast);
  2529. if (cast->cast_type == nullptr) {
  2530. push_error(R"(Expected type specifier after "as".)");
  2531. return p_previous_operand;
  2532. }
  2533. return cast;
  2534. }
  2535. GDScriptParser::ExpressionNode *GDScriptParser::parse_call(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2536. CallNode *call = alloc_node<CallNode>();
  2537. reset_extents(call, p_previous_operand);
  2538. if (previous.type == GDScriptTokenizer::Token::SUPER) {
  2539. // Super call.
  2540. call->is_super = true;
  2541. push_multiline(true);
  2542. if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  2543. // Implicit call to the parent method of the same name.
  2544. if (current_function == nullptr) {
  2545. push_error(R"(Cannot use implicit "super" call outside of a function.)");
  2546. pop_multiline();
  2547. complete_extents(call);
  2548. return nullptr;
  2549. }
  2550. if (current_function->identifier) {
  2551. call->function_name = current_function->identifier->name;
  2552. } else {
  2553. call->function_name = SNAME("<anonymous>");
  2554. }
  2555. } else {
  2556. consume(GDScriptTokenizer::Token::PERIOD, R"(Expected "." or "(" after "super".)");
  2557. make_completion_context(COMPLETION_SUPER_METHOD, call, true);
  2558. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after ".".)")) {
  2559. pop_multiline();
  2560. complete_extents(call);
  2561. return nullptr;
  2562. }
  2563. IdentifierNode *identifier = parse_identifier();
  2564. call->callee = identifier;
  2565. call->function_name = identifier->name;
  2566. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after function name.)");
  2567. }
  2568. } else {
  2569. call->callee = p_previous_operand;
  2570. if (call->callee == nullptr) {
  2571. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2572. } else if (call->callee->type == Node::IDENTIFIER) {
  2573. call->function_name = static_cast<IdentifierNode *>(call->callee)->name;
  2574. make_completion_context(COMPLETION_METHOD, call->callee);
  2575. } else if (call->callee->type == Node::SUBSCRIPT) {
  2576. SubscriptNode *attribute = static_cast<SubscriptNode *>(call->callee);
  2577. if (attribute->is_attribute) {
  2578. if (attribute->attribute) {
  2579. call->function_name = attribute->attribute->name;
  2580. }
  2581. make_completion_context(COMPLETION_ATTRIBUTE_METHOD, call->callee);
  2582. } else {
  2583. // TODO: The analyzer can see if this is actually a Callable and give better error message.
  2584. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2585. }
  2586. } else {
  2587. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2588. }
  2589. }
  2590. // Arguments.
  2591. CompletionType ct = COMPLETION_CALL_ARGUMENTS;
  2592. if (call->function_name == SNAME("load")) {
  2593. ct = COMPLETION_RESOURCE_PATH;
  2594. }
  2595. push_completion_call(call);
  2596. int argument_index = 0;
  2597. do {
  2598. make_completion_context(ct, call, argument_index++, true);
  2599. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  2600. // Allow for trailing comma.
  2601. break;
  2602. }
  2603. bool use_identifier_completion = current.cursor_place == GDScriptTokenizer::CURSOR_END || current.cursor_place == GDScriptTokenizer::CURSOR_MIDDLE;
  2604. ExpressionNode *argument = parse_expression(false);
  2605. if (argument == nullptr) {
  2606. push_error(R"(Expected expression as the function argument.)");
  2607. } else {
  2608. call->arguments.push_back(argument);
  2609. if (argument->type == Node::IDENTIFIER && use_identifier_completion) {
  2610. completion_context.type = COMPLETION_IDENTIFIER;
  2611. }
  2612. }
  2613. ct = COMPLETION_CALL_ARGUMENTS;
  2614. } while (match(GDScriptTokenizer::Token::COMMA));
  2615. pop_completion_call();
  2616. pop_multiline();
  2617. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after call arguments.)*");
  2618. complete_extents(call);
  2619. return call;
  2620. }
  2621. GDScriptParser::ExpressionNode *GDScriptParser::parse_get_node(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2622. if (!current.is_node_name() && !check(GDScriptTokenizer::Token::LITERAL) && !check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
  2623. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
  2624. return nullptr;
  2625. }
  2626. if (check(GDScriptTokenizer::Token::LITERAL)) {
  2627. if (current.literal.get_type() != Variant::STRING) {
  2628. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
  2629. return nullptr;
  2630. }
  2631. }
  2632. GetNodeNode *get_node = alloc_node<GetNodeNode>();
  2633. // Store the last item in the path so the parser knows what to expect.
  2634. // Allow allows more specific error messages.
  2635. enum PathState {
  2636. PATH_STATE_START,
  2637. PATH_STATE_SLASH,
  2638. PATH_STATE_PERCENT,
  2639. PATH_STATE_NODE_NAME,
  2640. } path_state = PATH_STATE_START;
  2641. if (previous.type == GDScriptTokenizer::Token::DOLLAR) {
  2642. // Detect initial slash, which will be handled in the loop if it matches.
  2643. match(GDScriptTokenizer::Token::SLASH);
  2644. #ifdef DEBUG_ENABLED
  2645. } else {
  2646. get_node->use_dollar = false;
  2647. #endif
  2648. }
  2649. int context_argument = 0;
  2650. do {
  2651. if (previous.type == GDScriptTokenizer::Token::PERCENT) {
  2652. if (path_state != PATH_STATE_START && path_state != PATH_STATE_SLASH) {
  2653. push_error(R"("%" is only valid in the beginning of a node name (either after "$" or after "/"))");
  2654. complete_extents(get_node);
  2655. return nullptr;
  2656. }
  2657. get_node->full_path += "%";
  2658. path_state = PATH_STATE_PERCENT;
  2659. } else if (previous.type == GDScriptTokenizer::Token::SLASH) {
  2660. if (path_state != PATH_STATE_START && path_state != PATH_STATE_NODE_NAME) {
  2661. push_error(R"("/" is only valid at the beginning of the path or after a node name.)");
  2662. complete_extents(get_node);
  2663. return nullptr;
  2664. }
  2665. get_node->full_path += "/";
  2666. path_state = PATH_STATE_SLASH;
  2667. }
  2668. make_completion_context(COMPLETION_GET_NODE, get_node, context_argument++);
  2669. if (match(GDScriptTokenizer::Token::LITERAL)) {
  2670. if (previous.literal.get_type() != Variant::STRING) {
  2671. String previous_token;
  2672. switch (path_state) {
  2673. case PATH_STATE_START:
  2674. previous_token = "$";
  2675. break;
  2676. case PATH_STATE_PERCENT:
  2677. previous_token = "%";
  2678. break;
  2679. case PATH_STATE_SLASH:
  2680. previous_token = "/";
  2681. break;
  2682. default:
  2683. break;
  2684. }
  2685. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous_token));
  2686. complete_extents(get_node);
  2687. return nullptr;
  2688. }
  2689. get_node->full_path += previous.literal.operator String();
  2690. path_state = PATH_STATE_NODE_NAME;
  2691. } else if (current.is_node_name()) {
  2692. advance();
  2693. String identifier = previous.get_identifier();
  2694. #ifdef DEBUG_ENABLED
  2695. // Check spoofing.
  2696. if (TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier)) {
  2697. push_warning(get_node, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier);
  2698. }
  2699. #endif
  2700. get_node->full_path += identifier;
  2701. path_state = PATH_STATE_NODE_NAME;
  2702. } else if (!check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
  2703. push_error(vformat(R"(Unexpected "%s" in node path.)", current.get_name()));
  2704. complete_extents(get_node);
  2705. return nullptr;
  2706. }
  2707. } while (match(GDScriptTokenizer::Token::SLASH) || match(GDScriptTokenizer::Token::PERCENT));
  2708. complete_extents(get_node);
  2709. return get_node;
  2710. }
  2711. GDScriptParser::ExpressionNode *GDScriptParser::parse_preload(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2712. PreloadNode *preload = alloc_node<PreloadNode>();
  2713. preload->resolved_path = "<missing path>";
  2714. push_multiline(true);
  2715. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "preload".)");
  2716. make_completion_context(COMPLETION_RESOURCE_PATH, preload);
  2717. push_completion_call(preload);
  2718. preload->path = parse_expression(false);
  2719. if (preload->path == nullptr) {
  2720. push_error(R"(Expected resource path after "(".)");
  2721. }
  2722. pop_completion_call();
  2723. pop_multiline();
  2724. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after preload path.)*");
  2725. complete_extents(preload);
  2726. return preload;
  2727. }
  2728. GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2729. LambdaNode *lambda = alloc_node<LambdaNode>();
  2730. lambda->parent_function = current_function;
  2731. FunctionNode *function = alloc_node<FunctionNode>();
  2732. function->source_lambda = lambda;
  2733. function->is_static = current_function != nullptr ? current_function->is_static : false;
  2734. if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
  2735. function->identifier = parse_identifier();
  2736. }
  2737. bool multiline_context = multiline_stack.back()->get();
  2738. // Reset the multiline stack since we don't want the multiline mode one in the lambda body.
  2739. push_multiline(false);
  2740. if (multiline_context) {
  2741. tokenizer.push_expression_indented_block();
  2742. }
  2743. push_multiline(true); // For the parameters.
  2744. if (function->identifier) {
  2745. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after lambda name.)");
  2746. } else {
  2747. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after "func".)");
  2748. }
  2749. FunctionNode *previous_function = current_function;
  2750. current_function = function;
  2751. SuiteNode *body = alloc_node<SuiteNode>();
  2752. body->parent_function = current_function;
  2753. body->parent_block = current_suite;
  2754. SuiteNode *previous_suite = current_suite;
  2755. current_suite = body;
  2756. parse_function_signature(function, body, "lambda");
  2757. current_suite = previous_suite;
  2758. bool previous_in_lambda = in_lambda;
  2759. in_lambda = true;
  2760. // Save break/continue state.
  2761. bool could_break = can_break;
  2762. bool could_continue = can_continue;
  2763. // Disallow break/continue.
  2764. can_break = false;
  2765. can_continue = false;
  2766. function->body = parse_suite("lambda declaration", body, true);
  2767. complete_extents(function);
  2768. complete_extents(lambda);
  2769. pop_multiline();
  2770. if (multiline_context) {
  2771. // If we're in multiline mode, we want to skip the spurious DEDENT and NEWLINE tokens.
  2772. while (check(GDScriptTokenizer::Token::DEDENT) || check(GDScriptTokenizer::Token::INDENT) || check(GDScriptTokenizer::Token::NEWLINE)) {
  2773. current = tokenizer.scan(); // Not advance() since we don't want to change the previous token.
  2774. }
  2775. tokenizer.pop_expression_indented_block();
  2776. }
  2777. current_function = previous_function;
  2778. in_lambda = previous_in_lambda;
  2779. lambda->function = function;
  2780. // Reset break/continue state.
  2781. can_break = could_break;
  2782. can_continue = could_continue;
  2783. return lambda;
  2784. }
  2785. GDScriptParser::ExpressionNode *GDScriptParser::parse_type_test(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2786. TypeTestNode *type_test = alloc_node<TypeTestNode>();
  2787. reset_extents(type_test, p_previous_operand);
  2788. update_extents(type_test);
  2789. type_test->operand = p_previous_operand;
  2790. type_test->test_type = parse_type();
  2791. complete_extents(type_test);
  2792. if (type_test->test_type == nullptr) {
  2793. push_error(R"(Expected type specifier after "is".)");
  2794. }
  2795. return type_test;
  2796. }
  2797. GDScriptParser::ExpressionNode *GDScriptParser::parse_yield(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2798. push_error(R"("yield" was removed in Godot 4.0. Use "await" instead.)");
  2799. return nullptr;
  2800. }
  2801. GDScriptParser::ExpressionNode *GDScriptParser::parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2802. // Just for better error messages.
  2803. GDScriptTokenizer::Token::Type invalid = previous.type;
  2804. switch (invalid) {
  2805. case GDScriptTokenizer::Token::QUESTION_MARK:
  2806. push_error(R"(Unexpected "?" in source. If you want a ternary operator, use "truthy_value if true_condition else falsy_value".)");
  2807. break;
  2808. default:
  2809. return nullptr; // Unreachable.
  2810. }
  2811. // Return the previous expression.
  2812. return p_previous_operand;
  2813. }
  2814. GDScriptParser::TypeNode *GDScriptParser::parse_type(bool p_allow_void) {
  2815. TypeNode *type = alloc_node<TypeNode>();
  2816. make_completion_context(p_allow_void ? COMPLETION_TYPE_NAME_OR_VOID : COMPLETION_TYPE_NAME, type);
  2817. if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
  2818. if (match(GDScriptTokenizer::Token::VOID)) {
  2819. if (p_allow_void) {
  2820. complete_extents(type);
  2821. TypeNode *void_type = type;
  2822. return void_type;
  2823. } else {
  2824. push_error(R"("void" is only allowed for a function return type.)");
  2825. }
  2826. }
  2827. // Leave error message to the caller who knows the context.
  2828. complete_extents(type);
  2829. return nullptr;
  2830. }
  2831. IdentifierNode *type_element = parse_identifier();
  2832. type->type_chain.push_back(type_element);
  2833. if (match(GDScriptTokenizer::Token::BRACKET_OPEN)) {
  2834. // Typed collection (like Array[int]).
  2835. type->container_type = parse_type(false); // Don't allow void for array element type.
  2836. if (type->container_type == nullptr) {
  2837. push_error(R"(Expected type for collection after "[".)");
  2838. complete_extents(type);
  2839. type = nullptr;
  2840. } else if (type->container_type->container_type != nullptr) {
  2841. push_error("Nested typed collections are not supported.");
  2842. }
  2843. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after collection type.)");
  2844. if (type != nullptr) {
  2845. complete_extents(type);
  2846. }
  2847. return type;
  2848. }
  2849. int chain_index = 1;
  2850. while (match(GDScriptTokenizer::Token::PERIOD)) {
  2851. make_completion_context(COMPLETION_TYPE_ATTRIBUTE, type, chain_index++);
  2852. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected inner type name after ".".)")) {
  2853. type_element = parse_identifier();
  2854. type->type_chain.push_back(type_element);
  2855. }
  2856. }
  2857. complete_extents(type);
  2858. return type;
  2859. }
  2860. #ifdef TOOLS_ENABLED
  2861. enum DocLineState {
  2862. DOC_LINE_NORMAL,
  2863. DOC_LINE_IN_CODE,
  2864. DOC_LINE_IN_CODEBLOCK,
  2865. };
  2866. static String _process_doc_line(const String &p_line, const String &p_text, const String &p_space_prefix, DocLineState &r_state) {
  2867. String line = p_line;
  2868. if (r_state == DOC_LINE_NORMAL) {
  2869. line = line.strip_edges(true, false);
  2870. } else {
  2871. line = line.trim_prefix(p_space_prefix);
  2872. }
  2873. String line_join;
  2874. if (!p_text.is_empty()) {
  2875. if (r_state == DOC_LINE_NORMAL) {
  2876. if (p_text.ends_with("[/codeblock]")) {
  2877. line_join = "\n";
  2878. } else if (!p_text.ends_with("[br]")) {
  2879. line_join = " ";
  2880. }
  2881. } else {
  2882. line_join = "\n";
  2883. }
  2884. }
  2885. String result;
  2886. int from = 0;
  2887. int buffer_start = 0;
  2888. const int len = line.length();
  2889. bool process = true;
  2890. while (process) {
  2891. switch (r_state) {
  2892. case DOC_LINE_NORMAL: {
  2893. int lb_pos = line.find_char('[', from);
  2894. if (lb_pos < 0) {
  2895. process = false;
  2896. break;
  2897. }
  2898. int rb_pos = line.find_char(']', lb_pos + 1);
  2899. if (rb_pos < 0) {
  2900. process = false;
  2901. break;
  2902. }
  2903. from = rb_pos + 1;
  2904. String tag = line.substr(lb_pos + 1, rb_pos - lb_pos - 1);
  2905. if (tag == "code") {
  2906. r_state = DOC_LINE_IN_CODE;
  2907. } else if (tag == "codeblock") {
  2908. if (lb_pos == 0) {
  2909. line_join = "\n";
  2910. } else {
  2911. result += line.substr(buffer_start, lb_pos - buffer_start) + '\n';
  2912. }
  2913. result += "[codeblock]";
  2914. if (from < len) {
  2915. result += '\n';
  2916. }
  2917. r_state = DOC_LINE_IN_CODEBLOCK;
  2918. buffer_start = from;
  2919. }
  2920. } break;
  2921. case DOC_LINE_IN_CODE: {
  2922. int pos = line.find("[/code]", from);
  2923. if (pos < 0) {
  2924. process = false;
  2925. break;
  2926. }
  2927. from = pos + 7;
  2928. r_state = DOC_LINE_NORMAL;
  2929. } break;
  2930. case DOC_LINE_IN_CODEBLOCK: {
  2931. int pos = line.find("[/codeblock]", from);
  2932. if (pos < 0) {
  2933. process = false;
  2934. break;
  2935. }
  2936. from = pos + 12;
  2937. if (pos == 0) {
  2938. line_join = "\n";
  2939. } else {
  2940. result += line.substr(buffer_start, pos - buffer_start) + '\n';
  2941. }
  2942. result += "[/codeblock]";
  2943. if (from < len) {
  2944. result += '\n';
  2945. }
  2946. r_state = DOC_LINE_NORMAL;
  2947. buffer_start = from;
  2948. } break;
  2949. }
  2950. }
  2951. result += line.substr(buffer_start);
  2952. if (r_state == DOC_LINE_NORMAL) {
  2953. result = result.strip_edges(false, true);
  2954. }
  2955. return line_join + result;
  2956. }
  2957. bool GDScriptParser::has_comment(int p_line, bool p_must_be_doc) {
  2958. bool has_comment = tokenizer.get_comments().has(p_line);
  2959. // If there are no comments or if we don't care whether the comment
  2960. // is a docstring, we have our result.
  2961. if (!p_must_be_doc || !has_comment) {
  2962. return has_comment;
  2963. }
  2964. return tokenizer.get_comments()[p_line].comment.begins_with("##");
  2965. }
  2966. String GDScriptParser::get_doc_comment(int p_line, bool p_single_line) {
  2967. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer.get_comments();
  2968. ERR_FAIL_COND_V(!comments.has(p_line), String());
  2969. if (p_single_line) {
  2970. if (comments[p_line].comment.begins_with("##")) {
  2971. return comments[p_line].comment.trim_prefix("##").strip_edges();
  2972. }
  2973. return "";
  2974. }
  2975. String doc;
  2976. int line = p_line;
  2977. DocLineState state = DOC_LINE_NORMAL;
  2978. while (comments.has(line - 1)) {
  2979. if (!comments[line - 1].new_line || !comments[line - 1].comment.begins_with("##")) {
  2980. break;
  2981. }
  2982. line--;
  2983. }
  2984. String space_prefix;
  2985. if (comments.has(line) && comments[line].comment.begins_with("##")) {
  2986. int i = 2;
  2987. for (; i < comments[line].comment.length(); i++) {
  2988. if (comments[line].comment[i] != ' ') {
  2989. break;
  2990. }
  2991. }
  2992. space_prefix = String(" ").repeat(i - 2);
  2993. }
  2994. while (comments.has(line)) {
  2995. if (!comments[line].new_line || !comments[line].comment.begins_with("##")) {
  2996. break;
  2997. }
  2998. String doc_line = comments[line].comment.trim_prefix("##");
  2999. doc += _process_doc_line(doc_line, doc, space_prefix, state);
  3000. line++;
  3001. }
  3002. return doc;
  3003. }
  3004. 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) {
  3005. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer.get_comments();
  3006. if (!comments.has(p_line)) {
  3007. return;
  3008. }
  3009. ERR_FAIL_COND(!p_brief.is_empty() || !p_desc.is_empty() || p_tutorials.size() != 0);
  3010. int line = p_line;
  3011. DocLineState state = DOC_LINE_NORMAL;
  3012. enum Mode {
  3013. BRIEF,
  3014. DESC,
  3015. TUTORIALS,
  3016. DONE,
  3017. };
  3018. Mode mode = BRIEF;
  3019. if (p_inner_class) {
  3020. while (comments.has(line - 1)) {
  3021. if (!comments[line - 1].new_line || !comments[line - 1].comment.begins_with("##")) {
  3022. break;
  3023. }
  3024. line--;
  3025. }
  3026. }
  3027. String space_prefix;
  3028. if (comments.has(line) && comments[line].comment.begins_with("##")) {
  3029. int i = 2;
  3030. for (; i < comments[line].comment.length(); i++) {
  3031. if (comments[line].comment[i] != ' ') {
  3032. break;
  3033. }
  3034. }
  3035. space_prefix = String(" ").repeat(i - 2);
  3036. }
  3037. while (comments.has(line)) {
  3038. if (!comments[line].new_line || !comments[line].comment.begins_with("##")) {
  3039. break;
  3040. }
  3041. String doc_line = comments[line++].comment.trim_prefix("##");
  3042. String title, link; // For tutorials.
  3043. if (state == DOC_LINE_NORMAL) {
  3044. // Set the read mode.
  3045. String stripped_line = doc_line.strip_edges();
  3046. if (stripped_line.is_empty()) {
  3047. if (mode == BRIEF && !p_brief.is_empty()) {
  3048. mode = DESC;
  3049. }
  3050. continue;
  3051. } else if (stripped_line.begins_with("@tutorial")) {
  3052. int begin_scan = String("@tutorial").length();
  3053. if (begin_scan >= stripped_line.length()) {
  3054. continue; // Invalid syntax.
  3055. }
  3056. if (stripped_line[begin_scan] == ':') { // No title.
  3057. // Syntax: ## @tutorial: https://godotengine.org/ // The title argument is optional.
  3058. title = "";
  3059. link = stripped_line.trim_prefix("@tutorial:").strip_edges();
  3060. } else {
  3061. /* Syntax:
  3062. * @tutorial ( The Title Here ) : https://the.url/
  3063. * ^ open ^ close ^ colon ^ url
  3064. */
  3065. int open_bracket_pos = begin_scan, close_bracket_pos = 0;
  3066. while (open_bracket_pos < stripped_line.length() && (stripped_line[open_bracket_pos] == ' ' || stripped_line[open_bracket_pos] == '\t')) {
  3067. open_bracket_pos++;
  3068. }
  3069. if (open_bracket_pos == stripped_line.length() || stripped_line[open_bracket_pos++] != '(') {
  3070. continue; // Invalid syntax.
  3071. }
  3072. close_bracket_pos = open_bracket_pos;
  3073. while (close_bracket_pos < stripped_line.length() && stripped_line[close_bracket_pos] != ')') {
  3074. close_bracket_pos++;
  3075. }
  3076. if (close_bracket_pos == stripped_line.length()) {
  3077. continue; // Invalid syntax.
  3078. }
  3079. int colon_pos = close_bracket_pos + 1;
  3080. while (colon_pos < stripped_line.length() && (stripped_line[colon_pos] == ' ' || stripped_line[colon_pos] == '\t')) {
  3081. colon_pos++;
  3082. }
  3083. if (colon_pos == stripped_line.length() || stripped_line[colon_pos++] != ':') {
  3084. continue; // Invalid syntax.
  3085. }
  3086. title = stripped_line.substr(open_bracket_pos, close_bracket_pos - open_bracket_pos).strip_edges();
  3087. link = stripped_line.substr(colon_pos).strip_edges();
  3088. }
  3089. mode = TUTORIALS;
  3090. } else if (mode == TUTORIALS) { // Tutorial docs are single line, we need a @tag after it.
  3091. mode = DONE;
  3092. }
  3093. }
  3094. switch (mode) {
  3095. case BRIEF:
  3096. p_brief += _process_doc_line(doc_line, p_brief, space_prefix, state);
  3097. break;
  3098. case DESC:
  3099. p_desc += _process_doc_line(doc_line, p_desc, space_prefix, state);
  3100. break;
  3101. case TUTORIALS:
  3102. p_tutorials.append(Pair<String, String>(title, link));
  3103. break;
  3104. case DONE:
  3105. break;
  3106. }
  3107. }
  3108. if (current_class->members.size() > 0) {
  3109. const ClassNode::Member &m = current_class->members[0];
  3110. int first_member_line = m.get_line();
  3111. if (first_member_line == line) {
  3112. p_brief = "";
  3113. p_desc = "";
  3114. p_tutorials.clear();
  3115. }
  3116. }
  3117. }
  3118. #endif // TOOLS_ENABLED
  3119. GDScriptParser::ParseRule *GDScriptParser::get_rule(GDScriptTokenizer::Token::Type p_token_type) {
  3120. // Function table for expression parsing.
  3121. // clang-format destroys the alignment here, so turn off for the table.
  3122. /* clang-format off */
  3123. static ParseRule rules[] = {
  3124. // PREFIX INFIX PRECEDENCE (for infix)
  3125. { nullptr, nullptr, PREC_NONE }, // EMPTY,
  3126. // Basic
  3127. { nullptr, nullptr, PREC_NONE }, // ANNOTATION,
  3128. { &GDScriptParser::parse_identifier, nullptr, PREC_NONE }, // IDENTIFIER,
  3129. { &GDScriptParser::parse_literal, nullptr, PREC_NONE }, // LITERAL,
  3130. // Comparison
  3131. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS,
  3132. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS_EQUAL,
  3133. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER,
  3134. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER_EQUAL,
  3135. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // EQUAL_EQUAL,
  3136. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // BANG_EQUAL,
  3137. // Logical
  3138. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AND,
  3139. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // OR,
  3140. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_not_in_operator, PREC_CONTENT_TEST }, // NOT,
  3141. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AMPERSAND_AMPERSAND,
  3142. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // PIPE_PIPE,
  3143. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // BANG,
  3144. // Bitwise
  3145. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_AND }, // AMPERSAND,
  3146. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_OR }, // PIPE,
  3147. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // TILDE,
  3148. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_XOR }, // CARET,
  3149. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // LESS_LESS,
  3150. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // GREATER_GREATER,
  3151. // Math
  3152. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // PLUS,
  3153. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // MINUS,
  3154. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // STAR,
  3155. { nullptr, &GDScriptParser::parse_binary_operator, PREC_POWER }, // STAR_STAR,
  3156. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // SLASH,
  3157. { &GDScriptParser::parse_get_node, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // PERCENT,
  3158. // Assignment
  3159. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // EQUAL,
  3160. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PLUS_EQUAL,
  3161. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // MINUS_EQUAL,
  3162. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_EQUAL,
  3163. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_STAR_EQUAL,
  3164. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // SLASH_EQUAL,
  3165. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PERCENT_EQUAL,
  3166. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // LESS_LESS_EQUAL,
  3167. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // GREATER_GREATER_EQUAL,
  3168. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // AMPERSAND_EQUAL,
  3169. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PIPE_EQUAL,
  3170. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // CARET_EQUAL,
  3171. // Control flow
  3172. { nullptr, &GDScriptParser::parse_ternary_operator, PREC_TERNARY }, // IF,
  3173. { nullptr, nullptr, PREC_NONE }, // ELIF,
  3174. { nullptr, nullptr, PREC_NONE }, // ELSE,
  3175. { nullptr, nullptr, PREC_NONE }, // FOR,
  3176. { nullptr, nullptr, PREC_NONE }, // WHILE,
  3177. { nullptr, nullptr, PREC_NONE }, // BREAK,
  3178. { nullptr, nullptr, PREC_NONE }, // CONTINUE,
  3179. { nullptr, nullptr, PREC_NONE }, // PASS,
  3180. { nullptr, nullptr, PREC_NONE }, // RETURN,
  3181. { nullptr, nullptr, PREC_NONE }, // MATCH,
  3182. // Keywords
  3183. { nullptr, &GDScriptParser::parse_cast, PREC_CAST }, // AS,
  3184. { nullptr, nullptr, PREC_NONE }, // ASSERT,
  3185. { &GDScriptParser::parse_await, nullptr, PREC_NONE }, // AWAIT,
  3186. { nullptr, nullptr, PREC_NONE }, // BREAKPOINT,
  3187. { nullptr, nullptr, PREC_NONE }, // CLASS,
  3188. { nullptr, nullptr, PREC_NONE }, // CLASS_NAME,
  3189. { nullptr, nullptr, PREC_NONE }, // CONST,
  3190. { nullptr, nullptr, PREC_NONE }, // ENUM,
  3191. { nullptr, nullptr, PREC_NONE }, // EXTENDS,
  3192. { &GDScriptParser::parse_lambda, nullptr, PREC_NONE }, // FUNC,
  3193. { nullptr, &GDScriptParser::parse_binary_operator, PREC_CONTENT_TEST }, // IN,
  3194. { nullptr, &GDScriptParser::parse_type_test, PREC_TYPE_TEST }, // IS,
  3195. { nullptr, nullptr, PREC_NONE }, // NAMESPACE,
  3196. { &GDScriptParser::parse_preload, nullptr, PREC_NONE }, // PRELOAD,
  3197. { &GDScriptParser::parse_self, nullptr, PREC_NONE }, // SELF,
  3198. { nullptr, nullptr, PREC_NONE }, // SIGNAL,
  3199. { nullptr, nullptr, PREC_NONE }, // STATIC,
  3200. { &GDScriptParser::parse_call, nullptr, PREC_NONE }, // SUPER,
  3201. { nullptr, nullptr, PREC_NONE }, // TRAIT,
  3202. { nullptr, nullptr, PREC_NONE }, // VAR,
  3203. { nullptr, nullptr, PREC_NONE }, // VOID,
  3204. { &GDScriptParser::parse_yield, nullptr, PREC_NONE }, // YIELD,
  3205. // Punctuation
  3206. { &GDScriptParser::parse_array, &GDScriptParser::parse_subscript, PREC_SUBSCRIPT }, // BRACKET_OPEN,
  3207. { nullptr, nullptr, PREC_NONE }, // BRACKET_CLOSE,
  3208. { &GDScriptParser::parse_dictionary, nullptr, PREC_NONE }, // BRACE_OPEN,
  3209. { nullptr, nullptr, PREC_NONE }, // BRACE_CLOSE,
  3210. { &GDScriptParser::parse_grouping, &GDScriptParser::parse_call, PREC_CALL }, // PARENTHESIS_OPEN,
  3211. { nullptr, nullptr, PREC_NONE }, // PARENTHESIS_CLOSE,
  3212. { nullptr, nullptr, PREC_NONE }, // COMMA,
  3213. { nullptr, nullptr, PREC_NONE }, // SEMICOLON,
  3214. { nullptr, &GDScriptParser::parse_attribute, PREC_ATTRIBUTE }, // PERIOD,
  3215. { nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD,
  3216. { nullptr, nullptr, PREC_NONE }, // COLON,
  3217. { &GDScriptParser::parse_get_node, nullptr, PREC_NONE }, // DOLLAR,
  3218. { nullptr, nullptr, PREC_NONE }, // FORWARD_ARROW,
  3219. { nullptr, nullptr, PREC_NONE }, // UNDERSCORE,
  3220. // Whitespace
  3221. { nullptr, nullptr, PREC_NONE }, // NEWLINE,
  3222. { nullptr, nullptr, PREC_NONE }, // INDENT,
  3223. { nullptr, nullptr, PREC_NONE }, // DEDENT,
  3224. // Constants
  3225. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_PI,
  3226. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_TAU,
  3227. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_INF,
  3228. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_NAN,
  3229. // Error message improvement
  3230. { nullptr, nullptr, PREC_NONE }, // VCS_CONFLICT_MARKER,
  3231. { nullptr, nullptr, PREC_NONE }, // BACKTICK,
  3232. { nullptr, &GDScriptParser::parse_invalid_token, PREC_CAST }, // QUESTION_MARK,
  3233. // Special
  3234. { nullptr, nullptr, PREC_NONE }, // ERROR,
  3235. { nullptr, nullptr, PREC_NONE }, // TK_EOF,
  3236. };
  3237. /* clang-format on */
  3238. // Avoid desync.
  3239. static_assert(sizeof(rules) / sizeof(rules[0]) == GDScriptTokenizer::Token::TK_MAX, "Amount of parse rules don't match the amount of token types.");
  3240. // Let's assume this is never invalid, since nothing generates a TK_MAX.
  3241. return &rules[p_token_type];
  3242. }
  3243. bool GDScriptParser::SuiteNode::has_local(const StringName &p_name) const {
  3244. if (locals_indices.has(p_name)) {
  3245. return true;
  3246. }
  3247. if (parent_block != nullptr) {
  3248. return parent_block->has_local(p_name);
  3249. }
  3250. return false;
  3251. }
  3252. const GDScriptParser::SuiteNode::Local &GDScriptParser::SuiteNode::get_local(const StringName &p_name) const {
  3253. if (locals_indices.has(p_name)) {
  3254. return locals[locals_indices[p_name]];
  3255. }
  3256. if (parent_block != nullptr) {
  3257. return parent_block->get_local(p_name);
  3258. }
  3259. return empty;
  3260. }
  3261. bool GDScriptParser::AnnotationNode::apply(GDScriptParser *p_this, Node *p_target) {
  3262. if (is_applied) {
  3263. return true;
  3264. }
  3265. is_applied = true;
  3266. return (p_this->*(p_this->valid_annotations[name].apply))(this, p_target);
  3267. }
  3268. bool GDScriptParser::AnnotationNode::applies_to(uint32_t p_target_kinds) const {
  3269. return (info->target_kind & p_target_kinds) > 0;
  3270. }
  3271. bool GDScriptParser::validate_annotation_arguments(AnnotationNode *p_annotation) {
  3272. ERR_FAIL_COND_V_MSG(!valid_annotations.has(p_annotation->name), false, vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
  3273. const MethodInfo &info = valid_annotations[p_annotation->name].info;
  3274. if (((info.flags & METHOD_FLAG_VARARG) == 0) && p_annotation->arguments.size() > info.arguments.size()) {
  3275. 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()));
  3276. return false;
  3277. }
  3278. if (p_annotation->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  3279. 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()));
  3280. return false;
  3281. }
  3282. // `@icon`'s argument needs to be resolved in the parser. See GH-72444.
  3283. if (p_annotation->name == SNAME("@icon")) {
  3284. ExpressionNode *argument = p_annotation->arguments[0];
  3285. if (argument->type != Node::LITERAL) {
  3286. push_error(R"(Argument 1 of annotation "@icon" must be a string literal.)", argument);
  3287. return false;
  3288. }
  3289. Variant value = static_cast<LiteralNode *>(argument)->value;
  3290. if (value.get_type() != Variant::STRING) {
  3291. push_error(R"(Argument 1 of annotation "@icon" must be a string literal.)", argument);
  3292. return false;
  3293. }
  3294. p_annotation->resolved_arguments.push_back(value);
  3295. }
  3296. // For other annotations, see `GDScriptAnalyzer::resolve_annotation()`.
  3297. return true;
  3298. }
  3299. bool GDScriptParser::tool_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  3300. #ifdef DEBUG_ENABLED
  3301. if (this->_is_tool) {
  3302. push_error(R"("@tool" annotation can only be used once.)", p_annotation);
  3303. return false;
  3304. }
  3305. #endif // DEBUG_ENABLED
  3306. this->_is_tool = true;
  3307. return true;
  3308. }
  3309. bool GDScriptParser::icon_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  3310. ERR_FAIL_COND_V_MSG(p_node->type != Node::CLASS, false, R"("@icon" annotation can only be applied to classes.)");
  3311. ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
  3312. ClassNode *p_class = static_cast<ClassNode *>(p_node);
  3313. #ifdef DEBUG_ENABLED
  3314. if (!p_class->icon_path.is_empty()) {
  3315. push_error(R"("@icon" annotation can only be used once.)", p_annotation);
  3316. return false;
  3317. }
  3318. if (String(p_annotation->resolved_arguments[0]).is_empty()) {
  3319. push_error(R"("@icon" annotation argument must contain the path to the icon.)", p_annotation->arguments[0]);
  3320. return false;
  3321. }
  3322. #endif // DEBUG_ENABLED
  3323. p_class->icon_path = p_annotation->resolved_arguments[0];
  3324. return true;
  3325. }
  3326. bool GDScriptParser::onready_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  3327. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, R"("@onready" annotation can only be applied to class variables.)");
  3328. if (current_class && !ClassDB::is_parent_class(current_class->get_datatype().native_type, SNAME("Node"))) {
  3329. push_error(R"("@onready" can only be used in classes that inherit "Node".)", p_annotation);
  3330. }
  3331. VariableNode *variable = static_cast<VariableNode *>(p_node);
  3332. if (variable->onready) {
  3333. push_error(R"("@onready" annotation can only be used once per variable.)");
  3334. return false;
  3335. }
  3336. variable->onready = true;
  3337. current_class->onready_used = true;
  3338. return true;
  3339. }
  3340. template <PropertyHint t_hint, Variant::Type t_type>
  3341. bool GDScriptParser::export_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  3342. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  3343. VariableNode *variable = static_cast<VariableNode *>(p_node);
  3344. if (variable->exported) {
  3345. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  3346. return false;
  3347. }
  3348. variable->exported = true;
  3349. variable->export_info.type = t_type;
  3350. variable->export_info.hint = t_hint;
  3351. String hint_string;
  3352. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  3353. String arg_string = String(p_annotation->resolved_arguments[i]);
  3354. if (p_annotation->name != SNAME("@export_placeholder")) {
  3355. if (arg_string.is_empty()) {
  3356. push_error(vformat(R"(Argument %d of annotation "%s" is empty.)", i + 1, p_annotation->name), p_annotation->arguments[i]);
  3357. return false;
  3358. }
  3359. if (arg_string.contains(",")) {
  3360. 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]);
  3361. return false;
  3362. }
  3363. }
  3364. if (p_annotation->name == SNAME("@export_flags")) {
  3365. const int64_t max_flags = 32;
  3366. Vector<String> t = arg_string.split(":", true, 1);
  3367. if (t[0].is_empty()) {
  3368. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag name.)", i + 1), p_annotation->arguments[i]);
  3369. return false;
  3370. }
  3371. if (t.size() == 2) {
  3372. if (t[1].is_empty()) {
  3373. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag value.)", i + 1), p_annotation->arguments[i]);
  3374. return false;
  3375. }
  3376. if (!t[1].is_valid_int()) {
  3377. 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]);
  3378. return false;
  3379. }
  3380. int64_t value = t[1].to_int();
  3381. if (value < 1 || value >= (1LL << max_flags)) {
  3382. 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]);
  3383. return false;
  3384. }
  3385. } else if (i >= max_flags) {
  3386. 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]);
  3387. return false;
  3388. }
  3389. }
  3390. if (i > 0) {
  3391. hint_string += ",";
  3392. }
  3393. hint_string += arg_string;
  3394. }
  3395. variable->export_info.hint_string = hint_string;
  3396. // This is called after the analyzer is done finding the type, so this should be set here.
  3397. DataType export_type = variable->get_datatype();
  3398. if (p_annotation->name == SNAME("@export_range")) {
  3399. if (export_type.builtin_type == Variant::INT) {
  3400. variable->export_info.type = Variant::INT;
  3401. }
  3402. }
  3403. if (p_annotation->name == SNAME("@export_multiline")) {
  3404. if (export_type.builtin_type == Variant::ARRAY && export_type.has_container_element_type()) {
  3405. DataType inner_type = export_type.get_container_element_type();
  3406. if (inner_type.builtin_type != Variant::STRING) {
  3407. 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);
  3408. return false;
  3409. }
  3410. String hint_prefix = itos(inner_type.builtin_type) + "/" + itos(variable->export_info.hint);
  3411. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  3412. variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
  3413. variable->export_info.type = Variant::ARRAY;
  3414. return true;
  3415. } else if (export_type.builtin_type == Variant::DICTIONARY) {
  3416. variable->export_info.type = Variant::DICTIONARY;
  3417. return true;
  3418. } else if (export_type.builtin_type == Variant::PACKED_STRING_ARRAY) {
  3419. String hint_prefix = itos(Variant::STRING) + "/" + itos(variable->export_info.hint);
  3420. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  3421. variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
  3422. variable->export_info.type = Variant::PACKED_STRING_ARRAY;
  3423. return true;
  3424. }
  3425. }
  3426. if (p_annotation->name == SNAME("@export")) {
  3427. if (variable->datatype_specifier == nullptr && variable->initializer == nullptr) {
  3428. push_error(R"(Cannot use simple "@export" annotation with variable without type or initializer, since type can't be inferred.)", p_annotation);
  3429. return false;
  3430. }
  3431. bool is_array = false;
  3432. if (export_type.builtin_type == Variant::ARRAY && export_type.has_container_element_type()) {
  3433. export_type = export_type.get_container_element_type(); // Use inner type for.
  3434. is_array = true;
  3435. }
  3436. if (export_type.is_variant() || export_type.has_no_type()) {
  3437. push_error(R"(Cannot use simple "@export" annotation because the type of the initialized value can't be inferred.)", p_annotation);
  3438. return false;
  3439. }
  3440. switch (export_type.kind) {
  3441. case GDScriptParser::DataType::BUILTIN:
  3442. variable->export_info.type = export_type.builtin_type;
  3443. variable->export_info.hint = PROPERTY_HINT_NONE;
  3444. variable->export_info.hint_string = Variant::get_type_name(export_type.builtin_type);
  3445. break;
  3446. case GDScriptParser::DataType::NATIVE:
  3447. if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
  3448. variable->export_info.type = Variant::OBJECT;
  3449. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  3450. variable->export_info.hint_string = export_type.native_type;
  3451. } else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
  3452. variable->export_info.type = Variant::OBJECT;
  3453. variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
  3454. variable->export_info.hint_string = export_type.native_type;
  3455. } else {
  3456. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", variable);
  3457. return false;
  3458. }
  3459. break;
  3460. case GDScriptParser::DataType::CLASS:
  3461. if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
  3462. variable->export_info.type = Variant::OBJECT;
  3463. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  3464. variable->export_info.hint_string = export_type.to_string();
  3465. } else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
  3466. variable->export_info.type = Variant::OBJECT;
  3467. variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
  3468. variable->export_info.hint_string = export_type.to_string();
  3469. } else {
  3470. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", variable);
  3471. return false;
  3472. }
  3473. break;
  3474. case GDScriptParser::DataType::SCRIPT: {
  3475. StringName class_name;
  3476. StringName native_base;
  3477. if (export_type.script_type.is_valid()) {
  3478. class_name = export_type.script_type->get_language()->get_global_class_name(export_type.script_type->get_path());
  3479. native_base = export_type.script_type->get_instance_base_type();
  3480. }
  3481. if (class_name == StringName()) {
  3482. Ref<Script> script = ResourceLoader::load(export_type.script_path, SNAME("Script"));
  3483. if (script.is_valid()) {
  3484. class_name = script->get_language()->get_global_class_name(export_type.script_path);
  3485. native_base = script->get_instance_base_type();
  3486. }
  3487. }
  3488. if (class_name != StringName() && native_base != StringName() && ClassDB::is_parent_class(native_base, SNAME("Resource"))) {
  3489. variable->export_info.type = Variant::OBJECT;
  3490. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  3491. variable->export_info.hint_string = class_name;
  3492. }
  3493. } break;
  3494. case GDScriptParser::DataType::ENUM: {
  3495. variable->export_info.type = Variant::INT;
  3496. variable->export_info.hint = PROPERTY_HINT_ENUM;
  3497. String enum_hint_string;
  3498. bool first = true;
  3499. for (const KeyValue<StringName, int64_t> &E : export_type.enum_values) {
  3500. if (!first) {
  3501. enum_hint_string += ",";
  3502. } else {
  3503. first = false;
  3504. }
  3505. enum_hint_string += E.key.operator String().capitalize().xml_escape();
  3506. enum_hint_string += ":";
  3507. enum_hint_string += String::num_int64(E.value).xml_escape();
  3508. }
  3509. variable->export_info.hint_string = enum_hint_string;
  3510. } break;
  3511. default:
  3512. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", variable);
  3513. break;
  3514. }
  3515. if (is_array) {
  3516. String hint_prefix = itos(variable->export_info.type);
  3517. if (variable->export_info.hint) {
  3518. hint_prefix += "/" + itos(variable->export_info.hint);
  3519. }
  3520. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  3521. variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
  3522. variable->export_info.type = Variant::ARRAY;
  3523. }
  3524. } else if (p_annotation->name == SNAME("@export_enum")) {
  3525. Variant::Type enum_type = Variant::INT;
  3526. if (export_type.kind == DataType::BUILTIN && export_type.builtin_type == Variant::STRING) {
  3527. enum_type = Variant::STRING;
  3528. } else if (export_type.is_variant() && variable->initializer != nullptr) {
  3529. DataType initializer_type = variable->initializer->get_datatype();
  3530. if (initializer_type.kind == DataType::BUILTIN && initializer_type.builtin_type == Variant::STRING) {
  3531. enum_type = Variant::STRING;
  3532. }
  3533. }
  3534. variable->export_info.type = enum_type;
  3535. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != enum_type)) {
  3536. 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);
  3537. return false;
  3538. }
  3539. } else {
  3540. // Validate variable type with export.
  3541. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != t_type)) {
  3542. // Allow float/int conversion.
  3543. if ((t_type != Variant::FLOAT || export_type.builtin_type != Variant::INT) && (t_type != Variant::INT || export_type.builtin_type != Variant::FLOAT)) {
  3544. 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);
  3545. return false;
  3546. }
  3547. }
  3548. }
  3549. return true;
  3550. }
  3551. template <PropertyUsageFlags t_usage>
  3552. bool GDScriptParser::export_group_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  3553. AnnotationNode *annotation = const_cast<AnnotationNode *>(p_annotation);
  3554. if (annotation->resolved_arguments.is_empty()) {
  3555. return false;
  3556. }
  3557. annotation->export_info.name = annotation->resolved_arguments[0];
  3558. switch (t_usage) {
  3559. case PROPERTY_USAGE_CATEGORY: {
  3560. annotation->export_info.usage = t_usage;
  3561. } break;
  3562. case PROPERTY_USAGE_GROUP: {
  3563. annotation->export_info.usage = t_usage;
  3564. if (annotation->resolved_arguments.size() == 2) {
  3565. annotation->export_info.hint_string = annotation->resolved_arguments[1];
  3566. }
  3567. } break;
  3568. case PROPERTY_USAGE_SUBGROUP: {
  3569. annotation->export_info.usage = t_usage;
  3570. if (annotation->resolved_arguments.size() == 2) {
  3571. annotation->export_info.hint_string = annotation->resolved_arguments[1];
  3572. }
  3573. } break;
  3574. }
  3575. return true;
  3576. }
  3577. bool GDScriptParser::warning_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  3578. #ifdef DEBUG_ENABLED
  3579. bool has_error = false;
  3580. for (const Variant &warning_name : p_annotation->resolved_arguments) {
  3581. GDScriptWarning::Code warning = GDScriptWarning::get_code_from_name(String(warning_name).to_upper());
  3582. if (warning == GDScriptWarning::WARNING_MAX) {
  3583. push_error(vformat(R"(Invalid warning name: "%s".)", warning_name), p_annotation);
  3584. has_error = true;
  3585. } else {
  3586. p_node->ignored_warnings.push_back(warning);
  3587. }
  3588. }
  3589. return !has_error;
  3590. #else // ! DEBUG_ENABLED
  3591. // Only available in debug builds.
  3592. return true;
  3593. #endif // DEBUG_ENABLED
  3594. }
  3595. bool GDScriptParser::rpc_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  3596. ERR_FAIL_COND_V_MSG(p_node->type != Node::FUNCTION, false, vformat(R"("%s" annotation can only be applied to functions.)", p_annotation->name));
  3597. FunctionNode *function = static_cast<FunctionNode *>(p_node);
  3598. if (function->rpc_config.get_type() != Variant::NIL) {
  3599. push_error(R"(RPC annotations can only be used once per function.)", p_annotation);
  3600. return false;
  3601. }
  3602. Dictionary rpc_config;
  3603. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
  3604. if (!p_annotation->resolved_arguments.is_empty()) {
  3605. unsigned char locality_args = 0;
  3606. unsigned char permission_args = 0;
  3607. unsigned char transfer_mode_args = 0;
  3608. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  3609. if (i == 3) {
  3610. rpc_config["channel"] = p_annotation->resolved_arguments[i].operator int();
  3611. continue;
  3612. }
  3613. String arg = p_annotation->resolved_arguments[i].operator String();
  3614. if (arg == "call_local") {
  3615. locality_args++;
  3616. rpc_config["call_local"] = true;
  3617. } else if (arg == "call_remote") {
  3618. locality_args++;
  3619. rpc_config["call_local"] = false;
  3620. } else if (arg == "any_peer") {
  3621. permission_args++;
  3622. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_ANY_PEER;
  3623. } else if (arg == "authority") {
  3624. permission_args++;
  3625. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
  3626. } else if (arg == "reliable") {
  3627. transfer_mode_args++;
  3628. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_RELIABLE;
  3629. } else if (arg == "unreliable") {
  3630. transfer_mode_args++;
  3631. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE;
  3632. } else if (arg == "unreliable_ordered") {
  3633. transfer_mode_args++;
  3634. rpc_config["transfer_mode"] = MultiplayerPeer::TRANSFER_MODE_UNRELIABLE_ORDERED;
  3635. } else {
  3636. 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);
  3637. }
  3638. }
  3639. if (locality_args > 1) {
  3640. push_error(R"(Invalid RPC config. The locality ("call_local"/"call_remote") must be specified no more than once.)", p_annotation);
  3641. } else if (permission_args > 1) {
  3642. push_error(R"(Invalid RPC config. The permission ("any_peer"/"authority") must be specified no more than once.)", p_annotation);
  3643. } else if (transfer_mode_args > 1) {
  3644. push_error(R"(Invalid RPC config. The transfer mode ("reliable"/"unreliable"/"unreliable_ordered") must be specified no more than once.)", p_annotation);
  3645. }
  3646. }
  3647. function->rpc_config = rpc_config;
  3648. return true;
  3649. }
  3650. bool GDScriptParser::static_unload_annotation(const AnnotationNode *p_annotation, Node *p_target) {
  3651. ERR_FAIL_COND_V_MSG(p_target->type != Node::CLASS, false, vformat(R"("%s" annotation can only be applied to classes.)", p_annotation->name));
  3652. ClassNode *p_class = static_cast<ClassNode *>(p_target);
  3653. if (p_class->annotated_static_unload) {
  3654. push_error(vformat(R"("%s" annotation can only be used once per script.)", p_annotation->name), p_annotation);
  3655. return false;
  3656. }
  3657. p_class->annotated_static_unload = true;
  3658. return true;
  3659. }
  3660. GDScriptParser::DataType GDScriptParser::SuiteNode::Local::get_datatype() const {
  3661. switch (type) {
  3662. case CONSTANT:
  3663. return constant->get_datatype();
  3664. case VARIABLE:
  3665. return variable->get_datatype();
  3666. case PARAMETER:
  3667. return parameter->get_datatype();
  3668. case FOR_VARIABLE:
  3669. case PATTERN_BIND:
  3670. return bind->get_datatype();
  3671. case UNDEFINED:
  3672. return DataType();
  3673. }
  3674. return DataType();
  3675. }
  3676. String GDScriptParser::SuiteNode::Local::get_name() const {
  3677. switch (type) {
  3678. case SuiteNode::Local::PARAMETER:
  3679. return "parameter";
  3680. case SuiteNode::Local::CONSTANT:
  3681. return "constant";
  3682. case SuiteNode::Local::VARIABLE:
  3683. return "variable";
  3684. case SuiteNode::Local::FOR_VARIABLE:
  3685. return "for loop iterator";
  3686. case SuiteNode::Local::PATTERN_BIND:
  3687. return "pattern_bind";
  3688. case SuiteNode::Local::UNDEFINED:
  3689. return "<undefined>";
  3690. default:
  3691. return String();
  3692. }
  3693. }
  3694. String GDScriptParser::DataType::to_string() const {
  3695. switch (kind) {
  3696. case VARIANT:
  3697. return "Variant";
  3698. case BUILTIN:
  3699. if (builtin_type == Variant::NIL) {
  3700. return "null";
  3701. }
  3702. if (builtin_type == Variant::ARRAY && has_container_element_type()) {
  3703. return vformat("Array[%s]", container_element_type->to_string());
  3704. }
  3705. return Variant::get_type_name(builtin_type);
  3706. case NATIVE:
  3707. if (is_meta_type) {
  3708. return GDScriptNativeClass::get_class_static();
  3709. }
  3710. return native_type.operator String();
  3711. case CLASS:
  3712. if (class_type->identifier != nullptr) {
  3713. return class_type->identifier->name.operator String();
  3714. }
  3715. return class_type->fqcn;
  3716. case SCRIPT: {
  3717. if (is_meta_type) {
  3718. return script_type != nullptr ? script_type->get_class_name().operator String() : "";
  3719. }
  3720. String name = script_type != nullptr ? script_type->get_name() : "";
  3721. if (!name.is_empty()) {
  3722. return name;
  3723. }
  3724. name = script_path;
  3725. if (!name.is_empty()) {
  3726. return name;
  3727. }
  3728. return native_type.operator String();
  3729. }
  3730. case ENUM: {
  3731. // native_type contains either the native class defining the enum
  3732. // or the fully qualified class name of the script defining the enum
  3733. return String(native_type).get_file(); // Remove path, keep filename
  3734. }
  3735. case RESOLVING:
  3736. case UNRESOLVED:
  3737. return "<unresolved type>";
  3738. }
  3739. ERR_FAIL_V_MSG("<unresolved type>", "Kind set outside the enum range.");
  3740. }
  3741. static Variant::Type _variant_type_to_typed_array_element_type(Variant::Type p_type) {
  3742. switch (p_type) {
  3743. case Variant::PACKED_BYTE_ARRAY:
  3744. case Variant::PACKED_INT32_ARRAY:
  3745. case Variant::PACKED_INT64_ARRAY:
  3746. return Variant::INT;
  3747. case Variant::PACKED_FLOAT32_ARRAY:
  3748. case Variant::PACKED_FLOAT64_ARRAY:
  3749. return Variant::FLOAT;
  3750. case Variant::PACKED_STRING_ARRAY:
  3751. return Variant::STRING;
  3752. case Variant::PACKED_VECTOR2_ARRAY:
  3753. return Variant::VECTOR2;
  3754. case Variant::PACKED_VECTOR3_ARRAY:
  3755. return Variant::VECTOR3;
  3756. case Variant::PACKED_COLOR_ARRAY:
  3757. return Variant::COLOR;
  3758. default:
  3759. return Variant::NIL;
  3760. }
  3761. }
  3762. bool GDScriptParser::DataType::is_typed_container_type() const {
  3763. return kind == GDScriptParser::DataType::BUILTIN && _variant_type_to_typed_array_element_type(builtin_type) != Variant::NIL;
  3764. }
  3765. GDScriptParser::DataType GDScriptParser::DataType::get_typed_container_type() const {
  3766. GDScriptParser::DataType type;
  3767. type.kind = GDScriptParser::DataType::BUILTIN;
  3768. type.builtin_type = _variant_type_to_typed_array_element_type(builtin_type);
  3769. return type;
  3770. }
  3771. void GDScriptParser::complete_extents(Node *p_node) {
  3772. while (!nodes_in_progress.is_empty() && nodes_in_progress.back()->get() != p_node) {
  3773. ERR_PRINT("Parser bug: Mismatch in extents tracking stack.");
  3774. nodes_in_progress.pop_back();
  3775. }
  3776. if (nodes_in_progress.is_empty()) {
  3777. ERR_PRINT("Parser bug: Extents tracking stack is empty.");
  3778. } else {
  3779. nodes_in_progress.pop_back();
  3780. }
  3781. }
  3782. void GDScriptParser::update_extents(Node *p_node) {
  3783. p_node->end_line = previous.end_line;
  3784. p_node->end_column = previous.end_column;
  3785. p_node->leftmost_column = MIN(p_node->leftmost_column, previous.leftmost_column);
  3786. p_node->rightmost_column = MAX(p_node->rightmost_column, previous.rightmost_column);
  3787. }
  3788. void GDScriptParser::reset_extents(Node *p_node, GDScriptTokenizer::Token p_token) {
  3789. p_node->start_line = p_token.start_line;
  3790. p_node->end_line = p_token.end_line;
  3791. p_node->start_column = p_token.start_column;
  3792. p_node->end_column = p_token.end_column;
  3793. p_node->leftmost_column = p_token.leftmost_column;
  3794. p_node->rightmost_column = p_token.rightmost_column;
  3795. }
  3796. void GDScriptParser::reset_extents(Node *p_node, Node *p_from) {
  3797. if (p_from == nullptr) {
  3798. return;
  3799. }
  3800. p_node->start_line = p_from->start_line;
  3801. p_node->end_line = p_from->end_line;
  3802. p_node->start_column = p_from->start_column;
  3803. p_node->end_column = p_from->end_column;
  3804. p_node->leftmost_column = p_from->leftmost_column;
  3805. p_node->rightmost_column = p_from->rightmost_column;
  3806. }
  3807. /*---------- PRETTY PRINT FOR DEBUG ----------*/
  3808. #ifdef DEBUG_ENABLED
  3809. void GDScriptParser::TreePrinter::increase_indent() {
  3810. indent_level++;
  3811. indent = "";
  3812. for (int i = 0; i < indent_level * 4; i++) {
  3813. if (i % 4 == 0) {
  3814. indent += "|";
  3815. } else {
  3816. indent += " ";
  3817. }
  3818. }
  3819. }
  3820. void GDScriptParser::TreePrinter::decrease_indent() {
  3821. indent_level--;
  3822. indent = "";
  3823. for (int i = 0; i < indent_level * 4; i++) {
  3824. if (i % 4 == 0) {
  3825. indent += "|";
  3826. } else {
  3827. indent += " ";
  3828. }
  3829. }
  3830. }
  3831. void GDScriptParser::TreePrinter::push_line(const String &p_line) {
  3832. if (!p_line.is_empty()) {
  3833. push_text(p_line);
  3834. }
  3835. printed += "\n";
  3836. pending_indent = true;
  3837. }
  3838. void GDScriptParser::TreePrinter::push_text(const String &p_text) {
  3839. if (pending_indent) {
  3840. printed += indent;
  3841. pending_indent = false;
  3842. }
  3843. printed += p_text;
  3844. }
  3845. void GDScriptParser::TreePrinter::print_annotation(const AnnotationNode *p_annotation) {
  3846. push_text(p_annotation->name);
  3847. push_text(" (");
  3848. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  3849. if (i > 0) {
  3850. push_text(" , ");
  3851. }
  3852. print_expression(p_annotation->arguments[i]);
  3853. }
  3854. push_line(")");
  3855. }
  3856. void GDScriptParser::TreePrinter::print_array(ArrayNode *p_array) {
  3857. push_text("[ ");
  3858. for (int i = 0; i < p_array->elements.size(); i++) {
  3859. if (i > 0) {
  3860. push_text(" , ");
  3861. }
  3862. print_expression(p_array->elements[i]);
  3863. }
  3864. push_text(" ]");
  3865. }
  3866. void GDScriptParser::TreePrinter::print_assert(AssertNode *p_assert) {
  3867. push_text("Assert ( ");
  3868. print_expression(p_assert->condition);
  3869. push_line(" )");
  3870. }
  3871. void GDScriptParser::TreePrinter::print_assignment(AssignmentNode *p_assignment) {
  3872. switch (p_assignment->assignee->type) {
  3873. case Node::IDENTIFIER:
  3874. print_identifier(static_cast<IdentifierNode *>(p_assignment->assignee));
  3875. break;
  3876. case Node::SUBSCRIPT:
  3877. print_subscript(static_cast<SubscriptNode *>(p_assignment->assignee));
  3878. break;
  3879. default:
  3880. break; // Unreachable.
  3881. }
  3882. push_text(" ");
  3883. switch (p_assignment->operation) {
  3884. case AssignmentNode::OP_ADDITION:
  3885. push_text("+");
  3886. break;
  3887. case AssignmentNode::OP_SUBTRACTION:
  3888. push_text("-");
  3889. break;
  3890. case AssignmentNode::OP_MULTIPLICATION:
  3891. push_text("*");
  3892. break;
  3893. case AssignmentNode::OP_DIVISION:
  3894. push_text("/");
  3895. break;
  3896. case AssignmentNode::OP_MODULO:
  3897. push_text("%");
  3898. break;
  3899. case AssignmentNode::OP_POWER:
  3900. push_text("**");
  3901. break;
  3902. case AssignmentNode::OP_BIT_SHIFT_LEFT:
  3903. push_text("<<");
  3904. break;
  3905. case AssignmentNode::OP_BIT_SHIFT_RIGHT:
  3906. push_text(">>");
  3907. break;
  3908. case AssignmentNode::OP_BIT_AND:
  3909. push_text("&");
  3910. break;
  3911. case AssignmentNode::OP_BIT_OR:
  3912. push_text("|");
  3913. break;
  3914. case AssignmentNode::OP_BIT_XOR:
  3915. push_text("^");
  3916. break;
  3917. case AssignmentNode::OP_NONE:
  3918. break;
  3919. }
  3920. push_text("= ");
  3921. print_expression(p_assignment->assigned_value);
  3922. push_line();
  3923. }
  3924. void GDScriptParser::TreePrinter::print_await(AwaitNode *p_await) {
  3925. push_text("Await ");
  3926. print_expression(p_await->to_await);
  3927. }
  3928. void GDScriptParser::TreePrinter::print_binary_op(BinaryOpNode *p_binary_op) {
  3929. // Surround in parenthesis for disambiguation.
  3930. push_text("(");
  3931. print_expression(p_binary_op->left_operand);
  3932. switch (p_binary_op->operation) {
  3933. case BinaryOpNode::OP_ADDITION:
  3934. push_text(" + ");
  3935. break;
  3936. case BinaryOpNode::OP_SUBTRACTION:
  3937. push_text(" - ");
  3938. break;
  3939. case BinaryOpNode::OP_MULTIPLICATION:
  3940. push_text(" * ");
  3941. break;
  3942. case BinaryOpNode::OP_DIVISION:
  3943. push_text(" / ");
  3944. break;
  3945. case BinaryOpNode::OP_MODULO:
  3946. push_text(" % ");
  3947. break;
  3948. case BinaryOpNode::OP_POWER:
  3949. push_text(" ** ");
  3950. break;
  3951. case BinaryOpNode::OP_BIT_LEFT_SHIFT:
  3952. push_text(" << ");
  3953. break;
  3954. case BinaryOpNode::OP_BIT_RIGHT_SHIFT:
  3955. push_text(" >> ");
  3956. break;
  3957. case BinaryOpNode::OP_BIT_AND:
  3958. push_text(" & ");
  3959. break;
  3960. case BinaryOpNode::OP_BIT_OR:
  3961. push_text(" | ");
  3962. break;
  3963. case BinaryOpNode::OP_BIT_XOR:
  3964. push_text(" ^ ");
  3965. break;
  3966. case BinaryOpNode::OP_LOGIC_AND:
  3967. push_text(" AND ");
  3968. break;
  3969. case BinaryOpNode::OP_LOGIC_OR:
  3970. push_text(" OR ");
  3971. break;
  3972. case BinaryOpNode::OP_CONTENT_TEST:
  3973. push_text(" IN ");
  3974. break;
  3975. case BinaryOpNode::OP_COMP_EQUAL:
  3976. push_text(" == ");
  3977. break;
  3978. case BinaryOpNode::OP_COMP_NOT_EQUAL:
  3979. push_text(" != ");
  3980. break;
  3981. case BinaryOpNode::OP_COMP_LESS:
  3982. push_text(" < ");
  3983. break;
  3984. case BinaryOpNode::OP_COMP_LESS_EQUAL:
  3985. push_text(" <= ");
  3986. break;
  3987. case BinaryOpNode::OP_COMP_GREATER:
  3988. push_text(" > ");
  3989. break;
  3990. case BinaryOpNode::OP_COMP_GREATER_EQUAL:
  3991. push_text(" >= ");
  3992. break;
  3993. }
  3994. print_expression(p_binary_op->right_operand);
  3995. // Surround in parenthesis for disambiguation.
  3996. push_text(")");
  3997. }
  3998. void GDScriptParser::TreePrinter::print_call(CallNode *p_call) {
  3999. if (p_call->is_super) {
  4000. push_text("super");
  4001. if (p_call->callee != nullptr) {
  4002. push_text(".");
  4003. print_expression(p_call->callee);
  4004. }
  4005. } else {
  4006. print_expression(p_call->callee);
  4007. }
  4008. push_text("( ");
  4009. for (int i = 0; i < p_call->arguments.size(); i++) {
  4010. if (i > 0) {
  4011. push_text(" , ");
  4012. }
  4013. print_expression(p_call->arguments[i]);
  4014. }
  4015. push_text(" )");
  4016. }
  4017. void GDScriptParser::TreePrinter::print_cast(CastNode *p_cast) {
  4018. print_expression(p_cast->operand);
  4019. push_text(" AS ");
  4020. print_type(p_cast->cast_type);
  4021. }
  4022. void GDScriptParser::TreePrinter::print_class(ClassNode *p_class) {
  4023. push_text("Class ");
  4024. if (p_class->identifier == nullptr) {
  4025. push_text("<unnamed>");
  4026. } else {
  4027. print_identifier(p_class->identifier);
  4028. }
  4029. if (p_class->extends_used) {
  4030. bool first = true;
  4031. push_text(" Extends ");
  4032. if (!p_class->extends_path.is_empty()) {
  4033. push_text(vformat(R"("%s")", p_class->extends_path));
  4034. first = false;
  4035. }
  4036. for (int i = 0; i < p_class->extends.size(); i++) {
  4037. if (!first) {
  4038. push_text(".");
  4039. } else {
  4040. first = false;
  4041. }
  4042. push_text(p_class->extends[i]->name);
  4043. }
  4044. }
  4045. push_line(" :");
  4046. increase_indent();
  4047. for (int i = 0; i < p_class->members.size(); i++) {
  4048. const ClassNode::Member &m = p_class->members[i];
  4049. switch (m.type) {
  4050. case ClassNode::Member::CLASS:
  4051. print_class(m.m_class);
  4052. break;
  4053. case ClassNode::Member::VARIABLE:
  4054. print_variable(m.variable);
  4055. break;
  4056. case ClassNode::Member::CONSTANT:
  4057. print_constant(m.constant);
  4058. break;
  4059. case ClassNode::Member::SIGNAL:
  4060. print_signal(m.signal);
  4061. break;
  4062. case ClassNode::Member::FUNCTION:
  4063. print_function(m.function);
  4064. break;
  4065. case ClassNode::Member::ENUM:
  4066. print_enum(m.m_enum);
  4067. break;
  4068. case ClassNode::Member::ENUM_VALUE:
  4069. break; // Nothing. Will be printed by enum.
  4070. case ClassNode::Member::GROUP:
  4071. break; // Nothing. Groups are only used by inspector.
  4072. case ClassNode::Member::UNDEFINED:
  4073. push_line("<unknown member>");
  4074. break;
  4075. }
  4076. }
  4077. decrease_indent();
  4078. }
  4079. void GDScriptParser::TreePrinter::print_constant(ConstantNode *p_constant) {
  4080. push_text("Constant ");
  4081. print_identifier(p_constant->identifier);
  4082. increase_indent();
  4083. push_line();
  4084. push_text("= ");
  4085. if (p_constant->initializer == nullptr) {
  4086. push_text("<missing value>");
  4087. } else {
  4088. print_expression(p_constant->initializer);
  4089. }
  4090. decrease_indent();
  4091. push_line();
  4092. }
  4093. void GDScriptParser::TreePrinter::print_dictionary(DictionaryNode *p_dictionary) {
  4094. push_line("{");
  4095. increase_indent();
  4096. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  4097. print_expression(p_dictionary->elements[i].key);
  4098. if (p_dictionary->style == DictionaryNode::PYTHON_DICT) {
  4099. push_text(" : ");
  4100. } else {
  4101. push_text(" = ");
  4102. }
  4103. print_expression(p_dictionary->elements[i].value);
  4104. push_line(" ,");
  4105. }
  4106. decrease_indent();
  4107. push_text("}");
  4108. }
  4109. void GDScriptParser::TreePrinter::print_expression(ExpressionNode *p_expression) {
  4110. if (p_expression == nullptr) {
  4111. push_text("<invalid expression>");
  4112. return;
  4113. }
  4114. switch (p_expression->type) {
  4115. case Node::ARRAY:
  4116. print_array(static_cast<ArrayNode *>(p_expression));
  4117. break;
  4118. case Node::ASSIGNMENT:
  4119. print_assignment(static_cast<AssignmentNode *>(p_expression));
  4120. break;
  4121. case Node::AWAIT:
  4122. print_await(static_cast<AwaitNode *>(p_expression));
  4123. break;
  4124. case Node::BINARY_OPERATOR:
  4125. print_binary_op(static_cast<BinaryOpNode *>(p_expression));
  4126. break;
  4127. case Node::CALL:
  4128. print_call(static_cast<CallNode *>(p_expression));
  4129. break;
  4130. case Node::CAST:
  4131. print_cast(static_cast<CastNode *>(p_expression));
  4132. break;
  4133. case Node::DICTIONARY:
  4134. print_dictionary(static_cast<DictionaryNode *>(p_expression));
  4135. break;
  4136. case Node::GET_NODE:
  4137. print_get_node(static_cast<GetNodeNode *>(p_expression));
  4138. break;
  4139. case Node::IDENTIFIER:
  4140. print_identifier(static_cast<IdentifierNode *>(p_expression));
  4141. break;
  4142. case Node::LAMBDA:
  4143. print_lambda(static_cast<LambdaNode *>(p_expression));
  4144. break;
  4145. case Node::LITERAL:
  4146. print_literal(static_cast<LiteralNode *>(p_expression));
  4147. break;
  4148. case Node::PRELOAD:
  4149. print_preload(static_cast<PreloadNode *>(p_expression));
  4150. break;
  4151. case Node::SELF:
  4152. print_self(static_cast<SelfNode *>(p_expression));
  4153. break;
  4154. case Node::SUBSCRIPT:
  4155. print_subscript(static_cast<SubscriptNode *>(p_expression));
  4156. break;
  4157. case Node::TERNARY_OPERATOR:
  4158. print_ternary_op(static_cast<TernaryOpNode *>(p_expression));
  4159. break;
  4160. case Node::TYPE_TEST:
  4161. print_type_test(static_cast<TypeTestNode *>(p_expression));
  4162. break;
  4163. case Node::UNARY_OPERATOR:
  4164. print_unary_op(static_cast<UnaryOpNode *>(p_expression));
  4165. break;
  4166. default:
  4167. push_text(vformat("<unknown expression %d>", p_expression->type));
  4168. break;
  4169. }
  4170. }
  4171. void GDScriptParser::TreePrinter::print_enum(EnumNode *p_enum) {
  4172. push_text("Enum ");
  4173. if (p_enum->identifier != nullptr) {
  4174. print_identifier(p_enum->identifier);
  4175. } else {
  4176. push_text("<unnamed>");
  4177. }
  4178. push_line(" {");
  4179. increase_indent();
  4180. for (int i = 0; i < p_enum->values.size(); i++) {
  4181. const EnumNode::Value &item = p_enum->values[i];
  4182. print_identifier(item.identifier);
  4183. push_text(" = ");
  4184. push_text(itos(item.value));
  4185. push_line(" ,");
  4186. }
  4187. decrease_indent();
  4188. push_line("}");
  4189. }
  4190. void GDScriptParser::TreePrinter::print_for(ForNode *p_for) {
  4191. push_text("For ");
  4192. print_identifier(p_for->variable);
  4193. push_text(" IN ");
  4194. print_expression(p_for->list);
  4195. push_line(" :");
  4196. increase_indent();
  4197. print_suite(p_for->loop);
  4198. decrease_indent();
  4199. }
  4200. void GDScriptParser::TreePrinter::print_function(FunctionNode *p_function, const String &p_context) {
  4201. for (const AnnotationNode *E : p_function->annotations) {
  4202. print_annotation(E);
  4203. }
  4204. push_text(p_context);
  4205. push_text(" ");
  4206. if (p_function->identifier) {
  4207. print_identifier(p_function->identifier);
  4208. } else {
  4209. push_text("<anonymous>");
  4210. }
  4211. push_text("( ");
  4212. for (int i = 0; i < p_function->parameters.size(); i++) {
  4213. if (i > 0) {
  4214. push_text(" , ");
  4215. }
  4216. print_parameter(p_function->parameters[i]);
  4217. }
  4218. push_line(" ) :");
  4219. increase_indent();
  4220. print_suite(p_function->body);
  4221. decrease_indent();
  4222. }
  4223. void GDScriptParser::TreePrinter::print_get_node(GetNodeNode *p_get_node) {
  4224. if (p_get_node->use_dollar) {
  4225. push_text("$");
  4226. }
  4227. push_text(p_get_node->full_path);
  4228. }
  4229. void GDScriptParser::TreePrinter::print_identifier(IdentifierNode *p_identifier) {
  4230. if (p_identifier != nullptr) {
  4231. push_text(p_identifier->name);
  4232. } else {
  4233. push_text("<invalid identifier>");
  4234. }
  4235. }
  4236. void GDScriptParser::TreePrinter::print_if(IfNode *p_if, bool p_is_elif) {
  4237. if (p_is_elif) {
  4238. push_text("Elif ");
  4239. } else {
  4240. push_text("If ");
  4241. }
  4242. print_expression(p_if->condition);
  4243. push_line(" :");
  4244. increase_indent();
  4245. print_suite(p_if->true_block);
  4246. decrease_indent();
  4247. // FIXME: Properly detect "elif" blocks.
  4248. if (p_if->false_block != nullptr) {
  4249. push_line("Else :");
  4250. increase_indent();
  4251. print_suite(p_if->false_block);
  4252. decrease_indent();
  4253. }
  4254. }
  4255. void GDScriptParser::TreePrinter::print_lambda(LambdaNode *p_lambda) {
  4256. print_function(p_lambda->function, "Lambda");
  4257. push_text("| captures [ ");
  4258. for (int i = 0; i < p_lambda->captures.size(); i++) {
  4259. if (i > 0) {
  4260. push_text(" , ");
  4261. }
  4262. push_text(p_lambda->captures[i]->name.operator String());
  4263. }
  4264. push_line(" ]");
  4265. }
  4266. void GDScriptParser::TreePrinter::print_literal(LiteralNode *p_literal) {
  4267. // Prefix for string types.
  4268. switch (p_literal->value.get_type()) {
  4269. case Variant::NODE_PATH:
  4270. push_text("^\"");
  4271. break;
  4272. case Variant::STRING:
  4273. push_text("\"");
  4274. break;
  4275. case Variant::STRING_NAME:
  4276. push_text("&\"");
  4277. break;
  4278. default:
  4279. break;
  4280. }
  4281. push_text(p_literal->value);
  4282. // Suffix for string types.
  4283. switch (p_literal->value.get_type()) {
  4284. case Variant::NODE_PATH:
  4285. case Variant::STRING:
  4286. case Variant::STRING_NAME:
  4287. push_text("\"");
  4288. break;
  4289. default:
  4290. break;
  4291. }
  4292. }
  4293. void GDScriptParser::TreePrinter::print_match(MatchNode *p_match) {
  4294. push_text("Match ");
  4295. print_expression(p_match->test);
  4296. push_line(" :");
  4297. increase_indent();
  4298. for (int i = 0; i < p_match->branches.size(); i++) {
  4299. print_match_branch(p_match->branches[i]);
  4300. }
  4301. decrease_indent();
  4302. }
  4303. void GDScriptParser::TreePrinter::print_match_branch(MatchBranchNode *p_match_branch) {
  4304. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  4305. if (i > 0) {
  4306. push_text(" , ");
  4307. }
  4308. print_match_pattern(p_match_branch->patterns[i]);
  4309. }
  4310. push_line(" :");
  4311. increase_indent();
  4312. print_suite(p_match_branch->block);
  4313. decrease_indent();
  4314. }
  4315. void GDScriptParser::TreePrinter::print_match_pattern(PatternNode *p_match_pattern) {
  4316. switch (p_match_pattern->pattern_type) {
  4317. case PatternNode::PT_LITERAL:
  4318. print_literal(p_match_pattern->literal);
  4319. break;
  4320. case PatternNode::PT_WILDCARD:
  4321. push_text("_");
  4322. break;
  4323. case PatternNode::PT_REST:
  4324. push_text("..");
  4325. break;
  4326. case PatternNode::PT_BIND:
  4327. push_text("Var ");
  4328. print_identifier(p_match_pattern->bind);
  4329. break;
  4330. case PatternNode::PT_EXPRESSION:
  4331. print_expression(p_match_pattern->expression);
  4332. break;
  4333. case PatternNode::PT_ARRAY:
  4334. push_text("[ ");
  4335. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  4336. if (i > 0) {
  4337. push_text(" , ");
  4338. }
  4339. print_match_pattern(p_match_pattern->array[i]);
  4340. }
  4341. push_text(" ]");
  4342. break;
  4343. case PatternNode::PT_DICTIONARY:
  4344. push_text("{ ");
  4345. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  4346. if (i > 0) {
  4347. push_text(" , ");
  4348. }
  4349. if (p_match_pattern->dictionary[i].key != nullptr) {
  4350. // Key can be null for rest pattern.
  4351. print_expression(p_match_pattern->dictionary[i].key);
  4352. push_text(" : ");
  4353. }
  4354. print_match_pattern(p_match_pattern->dictionary[i].value_pattern);
  4355. }
  4356. push_text(" }");
  4357. break;
  4358. }
  4359. }
  4360. void GDScriptParser::TreePrinter::print_parameter(ParameterNode *p_parameter) {
  4361. print_identifier(p_parameter->identifier);
  4362. if (p_parameter->datatype_specifier != nullptr) {
  4363. push_text(" : ");
  4364. print_type(p_parameter->datatype_specifier);
  4365. }
  4366. if (p_parameter->initializer != nullptr) {
  4367. push_text(" = ");
  4368. print_expression(p_parameter->initializer);
  4369. }
  4370. }
  4371. void GDScriptParser::TreePrinter::print_preload(PreloadNode *p_preload) {
  4372. push_text(R"(Preload ( ")");
  4373. push_text(p_preload->resolved_path);
  4374. push_text(R"(" )");
  4375. }
  4376. void GDScriptParser::TreePrinter::print_return(ReturnNode *p_return) {
  4377. push_text("Return");
  4378. if (p_return->return_value != nullptr) {
  4379. push_text(" ");
  4380. print_expression(p_return->return_value);
  4381. }
  4382. push_line();
  4383. }
  4384. void GDScriptParser::TreePrinter::print_self(SelfNode *p_self) {
  4385. push_text("Self(");
  4386. if (p_self->current_class->identifier != nullptr) {
  4387. print_identifier(p_self->current_class->identifier);
  4388. } else {
  4389. push_text("<main class>");
  4390. }
  4391. push_text(")");
  4392. }
  4393. void GDScriptParser::TreePrinter::print_signal(SignalNode *p_signal) {
  4394. push_text("Signal ");
  4395. print_identifier(p_signal->identifier);
  4396. push_text("( ");
  4397. for (int i = 0; i < p_signal->parameters.size(); i++) {
  4398. print_parameter(p_signal->parameters[i]);
  4399. }
  4400. push_line(" )");
  4401. }
  4402. void GDScriptParser::TreePrinter::print_subscript(SubscriptNode *p_subscript) {
  4403. print_expression(p_subscript->base);
  4404. if (p_subscript->is_attribute) {
  4405. push_text(".");
  4406. print_identifier(p_subscript->attribute);
  4407. } else {
  4408. push_text("[ ");
  4409. print_expression(p_subscript->index);
  4410. push_text(" ]");
  4411. }
  4412. }
  4413. void GDScriptParser::TreePrinter::print_statement(Node *p_statement) {
  4414. switch (p_statement->type) {
  4415. case Node::ASSERT:
  4416. print_assert(static_cast<AssertNode *>(p_statement));
  4417. break;
  4418. case Node::VARIABLE:
  4419. print_variable(static_cast<VariableNode *>(p_statement));
  4420. break;
  4421. case Node::CONSTANT:
  4422. print_constant(static_cast<ConstantNode *>(p_statement));
  4423. break;
  4424. case Node::IF:
  4425. print_if(static_cast<IfNode *>(p_statement));
  4426. break;
  4427. case Node::FOR:
  4428. print_for(static_cast<ForNode *>(p_statement));
  4429. break;
  4430. case Node::WHILE:
  4431. print_while(static_cast<WhileNode *>(p_statement));
  4432. break;
  4433. case Node::MATCH:
  4434. print_match(static_cast<MatchNode *>(p_statement));
  4435. break;
  4436. case Node::RETURN:
  4437. print_return(static_cast<ReturnNode *>(p_statement));
  4438. break;
  4439. case Node::BREAK:
  4440. push_line("Break");
  4441. break;
  4442. case Node::CONTINUE:
  4443. push_line("Continue");
  4444. break;
  4445. case Node::PASS:
  4446. push_line("Pass");
  4447. break;
  4448. case Node::BREAKPOINT:
  4449. push_line("Breakpoint");
  4450. break;
  4451. case Node::ASSIGNMENT:
  4452. print_assignment(static_cast<AssignmentNode *>(p_statement));
  4453. break;
  4454. default:
  4455. if (p_statement->is_expression()) {
  4456. print_expression(static_cast<ExpressionNode *>(p_statement));
  4457. push_line();
  4458. } else {
  4459. push_line(vformat("<unknown statement %d>", p_statement->type));
  4460. }
  4461. break;
  4462. }
  4463. }
  4464. void GDScriptParser::TreePrinter::print_suite(SuiteNode *p_suite) {
  4465. for (int i = 0; i < p_suite->statements.size(); i++) {
  4466. print_statement(p_suite->statements[i]);
  4467. }
  4468. }
  4469. void GDScriptParser::TreePrinter::print_ternary_op(TernaryOpNode *p_ternary_op) {
  4470. // Surround in parenthesis for disambiguation.
  4471. push_text("(");
  4472. print_expression(p_ternary_op->true_expr);
  4473. push_text(") IF (");
  4474. print_expression(p_ternary_op->condition);
  4475. push_text(") ELSE (");
  4476. print_expression(p_ternary_op->false_expr);
  4477. push_text(")");
  4478. }
  4479. void GDScriptParser::TreePrinter::print_type(TypeNode *p_type) {
  4480. if (p_type->type_chain.is_empty()) {
  4481. push_text("Void");
  4482. } else {
  4483. for (int i = 0; i < p_type->type_chain.size(); i++) {
  4484. if (i > 0) {
  4485. push_text(".");
  4486. }
  4487. print_identifier(p_type->type_chain[i]);
  4488. }
  4489. }
  4490. }
  4491. void GDScriptParser::TreePrinter::print_type_test(TypeTestNode *p_test) {
  4492. print_expression(p_test->operand);
  4493. push_text(" IS ");
  4494. print_type(p_test->test_type);
  4495. }
  4496. void GDScriptParser::TreePrinter::print_unary_op(UnaryOpNode *p_unary_op) {
  4497. // Surround in parenthesis for disambiguation.
  4498. push_text("(");
  4499. switch (p_unary_op->operation) {
  4500. case UnaryOpNode::OP_POSITIVE:
  4501. push_text("+");
  4502. break;
  4503. case UnaryOpNode::OP_NEGATIVE:
  4504. push_text("-");
  4505. break;
  4506. case UnaryOpNode::OP_LOGIC_NOT:
  4507. push_text("NOT");
  4508. break;
  4509. case UnaryOpNode::OP_COMPLEMENT:
  4510. push_text("~");
  4511. break;
  4512. }
  4513. print_expression(p_unary_op->operand);
  4514. // Surround in parenthesis for disambiguation.
  4515. push_text(")");
  4516. }
  4517. void GDScriptParser::TreePrinter::print_variable(VariableNode *p_variable) {
  4518. for (const AnnotationNode *E : p_variable->annotations) {
  4519. print_annotation(E);
  4520. }
  4521. push_text("Variable ");
  4522. print_identifier(p_variable->identifier);
  4523. push_text(" : ");
  4524. if (p_variable->datatype_specifier != nullptr) {
  4525. print_type(p_variable->datatype_specifier);
  4526. } else if (p_variable->infer_datatype) {
  4527. push_text("<inferred type>");
  4528. } else {
  4529. push_text("Variant");
  4530. }
  4531. increase_indent();
  4532. push_line();
  4533. push_text("= ");
  4534. if (p_variable->initializer == nullptr) {
  4535. push_text("<default value>");
  4536. } else {
  4537. print_expression(p_variable->initializer);
  4538. }
  4539. push_line();
  4540. if (p_variable->property != VariableNode::PROP_NONE) {
  4541. if (p_variable->getter != nullptr) {
  4542. push_text("Get");
  4543. if (p_variable->property == VariableNode::PROP_INLINE) {
  4544. push_line(":");
  4545. increase_indent();
  4546. print_suite(p_variable->getter->body);
  4547. decrease_indent();
  4548. } else {
  4549. push_line(" =");
  4550. increase_indent();
  4551. print_identifier(p_variable->getter_pointer);
  4552. push_line();
  4553. decrease_indent();
  4554. }
  4555. }
  4556. if (p_variable->setter != nullptr) {
  4557. push_text("Set (");
  4558. if (p_variable->property == VariableNode::PROP_INLINE) {
  4559. if (p_variable->setter_parameter != nullptr) {
  4560. print_identifier(p_variable->setter_parameter);
  4561. } else {
  4562. push_text("<missing>");
  4563. }
  4564. push_line("):");
  4565. increase_indent();
  4566. print_suite(p_variable->setter->body);
  4567. decrease_indent();
  4568. } else {
  4569. push_line(" =");
  4570. increase_indent();
  4571. print_identifier(p_variable->setter_pointer);
  4572. push_line();
  4573. decrease_indent();
  4574. }
  4575. }
  4576. }
  4577. decrease_indent();
  4578. push_line();
  4579. }
  4580. void GDScriptParser::TreePrinter::print_while(WhileNode *p_while) {
  4581. push_text("While ");
  4582. print_expression(p_while->condition);
  4583. push_line(" :");
  4584. increase_indent();
  4585. print_suite(p_while->loop);
  4586. decrease_indent();
  4587. }
  4588. void GDScriptParser::TreePrinter::print_tree(const GDScriptParser &p_parser) {
  4589. ERR_FAIL_COND_MSG(p_parser.get_tree() == nullptr, "Parse the code before printing the parse tree.");
  4590. if (p_parser.is_tool()) {
  4591. push_line("@tool");
  4592. }
  4593. if (!p_parser.get_tree()->icon_path.is_empty()) {
  4594. push_text(R"(@icon (")");
  4595. push_text(p_parser.get_tree()->icon_path);
  4596. push_line("\")");
  4597. }
  4598. print_class(p_parser.get_tree());
  4599. print_line(String(printed));
  4600. }
  4601. #endif // DEBUG_ENABLED