gdscript_parser.cpp 150 KB

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