gdscript_parser.cpp 155 KB

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