gdscript_parser.cpp 171 KB

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