gdscript_parser.cpp 161 KB

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