gdscript_parser.cpp 167 KB

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