gdscript_parser.cpp 179 KB

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