gdscript_parser.cpp 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490
  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 (Map<int, GDScriptTokenizer::CommentData>::Element *E = tokenizer.get_comments().front(); E; E = E->next()) {
  531. if (E->get().new_line && E->get().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 (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  938. do {
  939. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  940. // Allow for trailing comma.
  941. break;
  942. }
  943. ParameterNode *parameter = parse_parameter();
  944. if (parameter == nullptr) {
  945. push_error("Expected signal parameter name.");
  946. break;
  947. }
  948. if (parameter->default_value != nullptr) {
  949. push_error(R"(Signal parameters cannot have a default value.)");
  950. }
  951. if (signal->parameters_indices.has(parameter->identifier->name)) {
  952. push_error(vformat(R"(Parameter with name "%s" was already declared for this signal.)", parameter->identifier->name));
  953. } else {
  954. signal->parameters_indices[parameter->identifier->name] = signal->parameters.size();
  955. signal->parameters.push_back(parameter);
  956. }
  957. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  958. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after signal parameters.)*");
  959. }
  960. end_statement("signal declaration");
  961. return signal;
  962. }
  963. GDScriptParser::EnumNode *GDScriptParser::parse_enum() {
  964. EnumNode *enum_node = alloc_node<EnumNode>();
  965. bool named = false;
  966. if (check(GDScriptTokenizer::Token::IDENTIFIER)) {
  967. advance();
  968. enum_node->identifier = parse_identifier();
  969. named = true;
  970. }
  971. push_multiline(true);
  972. consume(GDScriptTokenizer::Token::BRACE_OPEN, vformat(R"(Expected "{" after %s.)", named ? "enum name" : R"("enum")"));
  973. HashMap<StringName, int> elements;
  974. do {
  975. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  976. break; // Allow trailing comma.
  977. }
  978. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for enum key.)")) {
  979. EnumNode::Value item;
  980. item.identifier = parse_identifier();
  981. item.parent_enum = enum_node;
  982. item.line = previous.start_line;
  983. item.leftmost_column = previous.leftmost_column;
  984. item.rightmost_column = previous.rightmost_column;
  985. if (elements.has(item.identifier->name)) {
  986. push_error(vformat(R"(Name "%s" was already in this enum (at line %d).)", item.identifier->name, elements[item.identifier->name]), item.identifier);
  987. } else if (!named) {
  988. // TODO: Abstract this recursive member check.
  989. ClassNode *parent = current_class;
  990. while (parent != nullptr) {
  991. if (parent->members_indices.has(item.identifier->name)) {
  992. 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()));
  993. break;
  994. }
  995. parent = parent->outer;
  996. }
  997. }
  998. elements[item.identifier->name] = item.line;
  999. if (match(GDScriptTokenizer::Token::EQUAL)) {
  1000. ExpressionNode *value = parse_expression(false);
  1001. if (value == nullptr) {
  1002. push_error(R"(Expected expression value after "=".)");
  1003. }
  1004. item.custom_value = value;
  1005. }
  1006. item.index = enum_node->values.size();
  1007. enum_node->values.push_back(item);
  1008. if (!named) {
  1009. // Add as member of current class.
  1010. current_class->add_member(item);
  1011. }
  1012. }
  1013. } while (match(GDScriptTokenizer::Token::COMMA));
  1014. pop_multiline();
  1015. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" for enum.)");
  1016. #ifdef TOOLS_ENABLED
  1017. // Enum values documentation.
  1018. for (int i = 0; i < enum_node->values.size(); i++) {
  1019. if (i == enum_node->values.size() - 1) {
  1020. // If close bracket is same line as last value.
  1021. if (enum_node->values[i].line != previous.start_line && has_comment(enum_node->values[i].line)) {
  1022. if (named) {
  1023. enum_node->values.write[i].doc_description = get_doc_comment(enum_node->values[i].line, true);
  1024. } else {
  1025. current_class->set_enum_value_doc(enum_node->values[i].identifier->name, get_doc_comment(enum_node->values[i].line, true));
  1026. }
  1027. }
  1028. } else {
  1029. // If two values are same line.
  1030. if (enum_node->values[i].line != enum_node->values[i + 1].line && has_comment(enum_node->values[i].line)) {
  1031. if (named) {
  1032. enum_node->values.write[i].doc_description = get_doc_comment(enum_node->values[i].line, true);
  1033. } else {
  1034. current_class->set_enum_value_doc(enum_node->values[i].identifier->name, get_doc_comment(enum_node->values[i].line, true));
  1035. }
  1036. }
  1037. }
  1038. }
  1039. #endif // TOOLS_ENABLED
  1040. end_statement("enum");
  1041. return enum_node;
  1042. }
  1043. void GDScriptParser::parse_function_signature(FunctionNode *p_function, SuiteNode *p_body, const String &p_type) {
  1044. if (!check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE) && !is_at_end()) {
  1045. bool default_used = false;
  1046. do {
  1047. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1048. // Allow for trailing comma.
  1049. break;
  1050. }
  1051. ParameterNode *parameter = parse_parameter();
  1052. if (parameter == nullptr) {
  1053. break;
  1054. }
  1055. if (parameter->default_value != nullptr) {
  1056. default_used = true;
  1057. } else {
  1058. if (default_used) {
  1059. push_error("Cannot have a mandatory parameters after optional parameters.");
  1060. continue;
  1061. }
  1062. }
  1063. if (p_function->parameters_indices.has(parameter->identifier->name)) {
  1064. push_error(vformat(R"(Parameter with name "%s" was already declared for this %s.)", parameter->identifier->name, p_type));
  1065. } else {
  1066. p_function->parameters_indices[parameter->identifier->name] = p_function->parameters.size();
  1067. p_function->parameters.push_back(parameter);
  1068. p_body->add_local(parameter, current_function);
  1069. }
  1070. } while (match(GDScriptTokenizer::Token::COMMA));
  1071. }
  1072. pop_multiline();
  1073. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, vformat(R"*(Expected closing ")" after %s parameters.)*", p_type));
  1074. if (match(GDScriptTokenizer::Token::FORWARD_ARROW)) {
  1075. make_completion_context(COMPLETION_TYPE_NAME_OR_VOID, p_function);
  1076. p_function->return_type = parse_type(true);
  1077. if (p_function->return_type == nullptr) {
  1078. push_error(R"(Expected return type or "void" after "->".)");
  1079. }
  1080. }
  1081. // TODO: Improve token consumption so it synchronizes to a statement boundary. This way we can get into the function body with unrecognized tokens.
  1082. consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after %s declaration.)", p_type));
  1083. }
  1084. GDScriptParser::FunctionNode *GDScriptParser::parse_function() {
  1085. bool _static = false;
  1086. if (previous.type == GDScriptTokenizer::Token::STATIC) {
  1087. // TODO: Improve message if user uses "static" with "var" or "const"
  1088. if (!consume(GDScriptTokenizer::Token::FUNC, R"(Expected "func" after "static".)")) {
  1089. return nullptr;
  1090. }
  1091. _static = true;
  1092. }
  1093. FunctionNode *function = alloc_node<FunctionNode>();
  1094. make_completion_context(COMPLETION_OVERRIDE_METHOD, function);
  1095. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after "func".)")) {
  1096. return nullptr;
  1097. }
  1098. FunctionNode *previous_function = current_function;
  1099. current_function = function;
  1100. function->identifier = parse_identifier();
  1101. function->is_static = _static;
  1102. SuiteNode *body = alloc_node<SuiteNode>();
  1103. SuiteNode *previous_suite = current_suite;
  1104. current_suite = body;
  1105. push_multiline(true);
  1106. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after function name.)");
  1107. parse_function_signature(function, body, "function");
  1108. current_suite = previous_suite;
  1109. function->body = parse_suite("function declaration", body);
  1110. current_function = previous_function;
  1111. return function;
  1112. }
  1113. GDScriptParser::AnnotationNode *GDScriptParser::parse_annotation(uint32_t p_valid_targets) {
  1114. AnnotationNode *annotation = alloc_node<AnnotationNode>();
  1115. annotation->name = previous.literal;
  1116. make_completion_context(COMPLETION_ANNOTATION, annotation);
  1117. bool valid = true;
  1118. if (!valid_annotations.has(annotation->name)) {
  1119. push_error(vformat(R"(Unrecognized annotation: "%s".)", annotation->name));
  1120. valid = false;
  1121. }
  1122. annotation->info = &valid_annotations[annotation->name];
  1123. if (!annotation->applies_to(p_valid_targets)) {
  1124. push_error(vformat(R"(Annotation "%s" is not allowed in this level.)", annotation->name));
  1125. valid = false;
  1126. }
  1127. if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  1128. // Arguments.
  1129. push_completion_call(annotation);
  1130. make_completion_context(COMPLETION_ANNOTATION_ARGUMENTS, annotation, 0, true);
  1131. if (!check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE) && !is_at_end()) {
  1132. int argument_index = 0;
  1133. do {
  1134. make_completion_context(COMPLETION_ANNOTATION_ARGUMENTS, annotation, argument_index, true);
  1135. set_last_completion_call_arg(argument_index++);
  1136. ExpressionNode *argument = parse_expression(false);
  1137. if (argument == nullptr) {
  1138. valid = false;
  1139. continue;
  1140. }
  1141. annotation->arguments.push_back(argument);
  1142. } while (match(GDScriptTokenizer::Token::COMMA));
  1143. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after annotation arguments.)*");
  1144. }
  1145. pop_completion_call();
  1146. }
  1147. match(GDScriptTokenizer::Token::NEWLINE); // Newline after annotation is optional.
  1148. if (valid) {
  1149. valid = validate_annotation_arguments(annotation);
  1150. }
  1151. return valid ? annotation : nullptr;
  1152. }
  1153. void GDScriptParser::clear_unused_annotations() {
  1154. for (const AnnotationNode *annotation : annotation_stack) {
  1155. push_error(vformat(R"(Annotation "%s" does not precedes a valid target, so it will have no effect.)", annotation->name), annotation);
  1156. }
  1157. annotation_stack.clear();
  1158. }
  1159. bool GDScriptParser::register_annotation(const MethodInfo &p_info, uint32_t p_target_kinds, AnnotationAction p_apply, int p_optional_arguments, bool p_is_vararg) {
  1160. ERR_FAIL_COND_V_MSG(valid_annotations.has(p_info.name), false, vformat(R"(Annotation "%s" already registered.)", p_info.name));
  1161. AnnotationInfo new_annotation;
  1162. new_annotation.info = p_info;
  1163. new_annotation.info.default_arguments.resize(p_optional_arguments);
  1164. if (p_is_vararg) {
  1165. new_annotation.info.flags |= METHOD_FLAG_VARARG;
  1166. }
  1167. new_annotation.apply = p_apply;
  1168. new_annotation.target_kind = p_target_kinds;
  1169. valid_annotations[p_info.name] = new_annotation;
  1170. return true;
  1171. }
  1172. GDScriptParser::SuiteNode *GDScriptParser::parse_suite(const String &p_context, SuiteNode *p_suite, bool p_for_lambda) {
  1173. SuiteNode *suite = p_suite != nullptr ? p_suite : alloc_node<SuiteNode>();
  1174. suite->parent_block = current_suite;
  1175. suite->parent_function = current_function;
  1176. current_suite = suite;
  1177. bool multiline = false;
  1178. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  1179. multiline = true;
  1180. }
  1181. if (multiline) {
  1182. if (!consume(GDScriptTokenizer::Token::INDENT, vformat(R"(Expected indented block after %s.)", p_context))) {
  1183. current_suite = suite->parent_block;
  1184. return suite;
  1185. }
  1186. }
  1187. int error_count = 0;
  1188. do {
  1189. if (!multiline && previous.type == GDScriptTokenizer::Token::SEMICOLON && check(GDScriptTokenizer::Token::NEWLINE)) {
  1190. break;
  1191. }
  1192. Node *statement = parse_statement();
  1193. if (statement == nullptr) {
  1194. if (error_count++ > 100) {
  1195. push_error("Too many statement errors.", suite);
  1196. break;
  1197. }
  1198. continue;
  1199. }
  1200. suite->statements.push_back(statement);
  1201. // Register locals.
  1202. switch (statement->type) {
  1203. case Node::VARIABLE: {
  1204. VariableNode *variable = static_cast<VariableNode *>(statement);
  1205. const SuiteNode::Local &local = current_suite->get_local(variable->identifier->name);
  1206. if (local.type != SuiteNode::Local::UNDEFINED) {
  1207. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), variable->identifier->name));
  1208. }
  1209. current_suite->add_local(variable, current_function);
  1210. break;
  1211. }
  1212. case Node::CONSTANT: {
  1213. ConstantNode *constant = static_cast<ConstantNode *>(statement);
  1214. const SuiteNode::Local &local = current_suite->get_local(constant->identifier->name);
  1215. if (local.type != SuiteNode::Local::UNDEFINED) {
  1216. String name;
  1217. if (local.type == SuiteNode::Local::CONSTANT) {
  1218. name = "constant";
  1219. } else {
  1220. name = "variable";
  1221. }
  1222. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", name, constant->identifier->name));
  1223. }
  1224. current_suite->add_local(constant, current_function);
  1225. break;
  1226. }
  1227. default:
  1228. break;
  1229. }
  1230. } while ((multiline || previous.type == GDScriptTokenizer::Token::SEMICOLON) && !check(GDScriptTokenizer::Token::DEDENT) && !lambda_ended && !is_at_end());
  1231. if (multiline) {
  1232. if (!lambda_ended) {
  1233. consume(GDScriptTokenizer::Token::DEDENT, vformat(R"(Missing unindent at the end of %s.)", p_context));
  1234. } else {
  1235. match(GDScriptTokenizer::Token::DEDENT);
  1236. }
  1237. } else if (previous.type == GDScriptTokenizer::Token::SEMICOLON) {
  1238. consume(GDScriptTokenizer::Token::NEWLINE, vformat(R"(Expected newline after ";" at the end of %s.)", p_context));
  1239. }
  1240. if (p_for_lambda) {
  1241. lambda_ended = true;
  1242. }
  1243. current_suite = suite->parent_block;
  1244. return suite;
  1245. }
  1246. GDScriptParser::Node *GDScriptParser::parse_statement() {
  1247. Node *result = nullptr;
  1248. #ifdef DEBUG_ENABLED
  1249. bool unreachable = current_suite->has_return && !current_suite->has_unreachable_code;
  1250. #endif
  1251. switch (current.type) {
  1252. case GDScriptTokenizer::Token::PASS:
  1253. advance();
  1254. result = alloc_node<PassNode>();
  1255. end_statement(R"("pass")");
  1256. break;
  1257. case GDScriptTokenizer::Token::VAR:
  1258. advance();
  1259. result = parse_variable();
  1260. break;
  1261. case GDScriptTokenizer::Token::CONST:
  1262. advance();
  1263. result = parse_constant();
  1264. break;
  1265. case GDScriptTokenizer::Token::IF:
  1266. advance();
  1267. result = parse_if();
  1268. break;
  1269. case GDScriptTokenizer::Token::FOR:
  1270. advance();
  1271. result = parse_for();
  1272. break;
  1273. case GDScriptTokenizer::Token::WHILE:
  1274. advance();
  1275. result = parse_while();
  1276. break;
  1277. case GDScriptTokenizer::Token::MATCH:
  1278. advance();
  1279. result = parse_match();
  1280. break;
  1281. case GDScriptTokenizer::Token::BREAK:
  1282. advance();
  1283. result = parse_break();
  1284. break;
  1285. case GDScriptTokenizer::Token::CONTINUE:
  1286. advance();
  1287. result = parse_continue();
  1288. break;
  1289. case GDScriptTokenizer::Token::RETURN: {
  1290. advance();
  1291. ReturnNode *n_return = alloc_node<ReturnNode>();
  1292. if (!is_statement_end()) {
  1293. if (current_function && current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._init) {
  1294. push_error(R"(Constructor cannot return a value.)");
  1295. }
  1296. n_return->return_value = parse_expression(false);
  1297. } else if (in_lambda && !is_statement_end_token()) {
  1298. // Try to parse it anyway as this might not be the statement end in a lambda.
  1299. // If this fails the expression will be nullptr, but that's the same as no return, so it's fine.
  1300. n_return->return_value = parse_expression(false);
  1301. }
  1302. result = n_return;
  1303. current_suite->has_return = true;
  1304. end_statement("return statement");
  1305. break;
  1306. }
  1307. case GDScriptTokenizer::Token::BREAKPOINT:
  1308. advance();
  1309. result = alloc_node<BreakpointNode>();
  1310. end_statement(R"("breakpoint")");
  1311. break;
  1312. case GDScriptTokenizer::Token::ASSERT:
  1313. advance();
  1314. result = parse_assert();
  1315. break;
  1316. case GDScriptTokenizer::Token::ANNOTATION: {
  1317. advance();
  1318. AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT);
  1319. if (annotation != nullptr) {
  1320. annotation_stack.push_back(annotation);
  1321. }
  1322. break;
  1323. }
  1324. default: {
  1325. // Expression statement.
  1326. ExpressionNode *expression = parse_expression(true); // Allow assignment here.
  1327. bool has_ended_lambda = false;
  1328. if (expression == nullptr) {
  1329. if (in_lambda) {
  1330. // If it's not a valid expression beginning, it might be the continuation of the outer expression where this lambda is.
  1331. lambda_ended = true;
  1332. has_ended_lambda = true;
  1333. } else {
  1334. push_error(vformat(R"(Expected statement, found "%s" instead.)", previous.get_name()));
  1335. }
  1336. }
  1337. end_statement("expression");
  1338. lambda_ended = lambda_ended || has_ended_lambda;
  1339. result = expression;
  1340. #ifdef DEBUG_ENABLED
  1341. if (expression != nullptr) {
  1342. switch (expression->type) {
  1343. case Node::CALL:
  1344. case Node::ASSIGNMENT:
  1345. case Node::AWAIT:
  1346. // Fine.
  1347. break;
  1348. default:
  1349. push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
  1350. }
  1351. }
  1352. #endif
  1353. break;
  1354. }
  1355. }
  1356. #ifdef DEBUG_ENABLED
  1357. if (unreachable && result != nullptr) {
  1358. current_suite->has_unreachable_code = true;
  1359. if (current_function) {
  1360. push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier ? current_function->identifier->name : "<anonymous lambda>");
  1361. } else {
  1362. // TODO: Properties setters and getters with unreachable code are not being warned
  1363. }
  1364. }
  1365. #endif
  1366. if (panic_mode) {
  1367. synchronize();
  1368. }
  1369. return result;
  1370. }
  1371. GDScriptParser::AssertNode *GDScriptParser::parse_assert() {
  1372. // TODO: Add assert message.
  1373. AssertNode *assert = alloc_node<AssertNode>();
  1374. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "assert".)");
  1375. assert->condition = parse_expression(false);
  1376. if (assert->condition == nullptr) {
  1377. push_error("Expected expression to assert.");
  1378. return nullptr;
  1379. }
  1380. if (match(GDScriptTokenizer::Token::COMMA)) {
  1381. // Error message.
  1382. assert->message = parse_expression(false);
  1383. if (assert->message == nullptr) {
  1384. push_error(R"(Expected error message for assert after ",".)");
  1385. return nullptr;
  1386. }
  1387. }
  1388. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after assert expression.)*");
  1389. end_statement(R"("assert")");
  1390. return assert;
  1391. }
  1392. GDScriptParser::BreakNode *GDScriptParser::parse_break() {
  1393. if (!can_break) {
  1394. push_error(R"(Cannot use "break" outside of a loop.)");
  1395. }
  1396. end_statement(R"("break")");
  1397. return alloc_node<BreakNode>();
  1398. }
  1399. GDScriptParser::ContinueNode *GDScriptParser::parse_continue() {
  1400. if (!can_continue) {
  1401. push_error(R"(Cannot use "continue" outside of a loop or pattern matching block.)");
  1402. }
  1403. current_suite->has_continue = true;
  1404. end_statement(R"("continue")");
  1405. ContinueNode *cont = alloc_node<ContinueNode>();
  1406. cont->is_for_match = is_continue_match;
  1407. return cont;
  1408. }
  1409. GDScriptParser::ForNode *GDScriptParser::parse_for() {
  1410. ForNode *n_for = alloc_node<ForNode>();
  1411. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected loop variable name after "for".)")) {
  1412. n_for->variable = parse_identifier();
  1413. }
  1414. consume(GDScriptTokenizer::Token::IN, R"(Expected "in" after "for" variable name.)");
  1415. n_for->list = parse_expression(false);
  1416. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "for" condition.)");
  1417. // Save break/continue state.
  1418. bool could_break = can_break;
  1419. bool could_continue = can_continue;
  1420. bool was_continue_match = is_continue_match;
  1421. // Allow break/continue.
  1422. can_break = true;
  1423. can_continue = true;
  1424. is_continue_match = false;
  1425. SuiteNode *suite = alloc_node<SuiteNode>();
  1426. if (n_for->variable) {
  1427. suite->add_local(SuiteNode::Local(n_for->variable, current_function));
  1428. }
  1429. suite->parent_for = n_for;
  1430. n_for->loop = parse_suite(R"("for" block)", suite);
  1431. // Reset break/continue state.
  1432. can_break = could_break;
  1433. can_continue = could_continue;
  1434. is_continue_match = was_continue_match;
  1435. return n_for;
  1436. }
  1437. GDScriptParser::IfNode *GDScriptParser::parse_if(const String &p_token) {
  1438. IfNode *n_if = alloc_node<IfNode>();
  1439. n_if->condition = parse_expression(false);
  1440. if (n_if->condition == nullptr) {
  1441. push_error(vformat(R"(Expected conditional expression after "%s".)", p_token));
  1442. }
  1443. consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after "%s" condition.)", p_token));
  1444. n_if->true_block = parse_suite(vformat(R"("%s" block)", p_token));
  1445. n_if->true_block->parent_if = n_if;
  1446. if (n_if->true_block->has_continue) {
  1447. current_suite->has_continue = true;
  1448. }
  1449. if (match(GDScriptTokenizer::Token::ELIF)) {
  1450. IfNode *elif = parse_if("elif");
  1451. SuiteNode *else_block = alloc_node<SuiteNode>();
  1452. else_block->statements.push_back(elif);
  1453. n_if->false_block = else_block;
  1454. } else if (match(GDScriptTokenizer::Token::ELSE)) {
  1455. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "else".)");
  1456. n_if->false_block = parse_suite(R"("else" block)");
  1457. }
  1458. if (n_if->false_block != nullptr && n_if->false_block->has_return && n_if->true_block->has_return) {
  1459. current_suite->has_return = true;
  1460. }
  1461. if (n_if->false_block != nullptr && n_if->false_block->has_continue) {
  1462. current_suite->has_continue = true;
  1463. }
  1464. return n_if;
  1465. }
  1466. GDScriptParser::MatchNode *GDScriptParser::parse_match() {
  1467. MatchNode *match = alloc_node<MatchNode>();
  1468. match->test = parse_expression(false);
  1469. if (match->test == nullptr) {
  1470. push_error(R"(Expected expression to test after "match".)");
  1471. }
  1472. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" expression.)");
  1473. consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected a newline after "match" statement.)");
  1474. if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected an indented block after "match" statement.)")) {
  1475. return match;
  1476. }
  1477. #ifdef DEBUG_ENABLED
  1478. bool all_have_return = true;
  1479. bool have_wildcard = false;
  1480. bool wildcard_has_return = false;
  1481. bool have_wildcard_without_continue = false;
  1482. #endif
  1483. while (!check(GDScriptTokenizer::Token::DEDENT) && !is_at_end()) {
  1484. MatchBranchNode *branch = parse_match_branch();
  1485. if (branch == nullptr) {
  1486. advance();
  1487. continue;
  1488. }
  1489. #ifdef DEBUG_ENABLED
  1490. if (have_wildcard_without_continue) {
  1491. push_warning(branch->patterns[0], GDScriptWarning::UNREACHABLE_PATTERN);
  1492. }
  1493. if (branch->has_wildcard) {
  1494. have_wildcard = true;
  1495. if (branch->block->has_return) {
  1496. wildcard_has_return = true;
  1497. }
  1498. if (!branch->block->has_continue) {
  1499. have_wildcard_without_continue = true;
  1500. }
  1501. }
  1502. if (!branch->block->has_return) {
  1503. all_have_return = false;
  1504. }
  1505. #endif
  1506. match->branches.push_back(branch);
  1507. }
  1508. consume(GDScriptTokenizer::Token::DEDENT, R"(Expected an indented block after "match" statement.)");
  1509. #ifdef DEBUG_ENABLED
  1510. if (wildcard_has_return || (all_have_return && have_wildcard)) {
  1511. current_suite->has_return = true;
  1512. }
  1513. #endif
  1514. return match;
  1515. }
  1516. GDScriptParser::MatchBranchNode *GDScriptParser::parse_match_branch() {
  1517. MatchBranchNode *branch = alloc_node<MatchBranchNode>();
  1518. bool has_bind = false;
  1519. do {
  1520. PatternNode *pattern = parse_match_pattern();
  1521. if (pattern == nullptr) {
  1522. continue;
  1523. }
  1524. if (pattern->pattern_type == PatternNode::PT_BIND) {
  1525. has_bind = true;
  1526. }
  1527. if (branch->patterns.size() > 0 && has_bind) {
  1528. push_error(R"(Cannot use a variable bind with multiple patterns.)");
  1529. }
  1530. if (pattern->pattern_type == PatternNode::PT_REST) {
  1531. push_error(R"(Rest pattern can only be used inside array and dictionary patterns.)");
  1532. } else if (pattern->pattern_type == PatternNode::PT_BIND || pattern->pattern_type == PatternNode::PT_WILDCARD) {
  1533. branch->has_wildcard = true;
  1534. }
  1535. branch->patterns.push_back(pattern);
  1536. } while (match(GDScriptTokenizer::Token::COMMA));
  1537. if (branch->patterns.is_empty()) {
  1538. push_error(R"(No pattern found for "match" branch.)");
  1539. }
  1540. if (!consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" patterns.)")) {
  1541. return nullptr;
  1542. }
  1543. // Save continue state.
  1544. bool could_continue = can_continue;
  1545. bool was_continue_match = is_continue_match;
  1546. // Allow continue for match.
  1547. can_continue = true;
  1548. is_continue_match = true;
  1549. SuiteNode *suite = alloc_node<SuiteNode>();
  1550. if (branch->patterns.size() > 0) {
  1551. List<StringName> binds;
  1552. branch->patterns[0]->binds.get_key_list(&binds);
  1553. for (const StringName &E : binds) {
  1554. SuiteNode::Local local(branch->patterns[0]->binds[E], current_function);
  1555. suite->add_local(local);
  1556. }
  1557. }
  1558. branch->block = parse_suite("match pattern block", suite);
  1559. // Restore continue state.
  1560. can_continue = could_continue;
  1561. is_continue_match = was_continue_match;
  1562. return branch;
  1563. }
  1564. GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_root_pattern) {
  1565. PatternNode *pattern = alloc_node<PatternNode>();
  1566. switch (current.type) {
  1567. case GDScriptTokenizer::Token::VAR: {
  1568. // Bind.
  1569. advance();
  1570. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected bind name after "var".)")) {
  1571. return nullptr;
  1572. }
  1573. pattern->pattern_type = PatternNode::PT_BIND;
  1574. pattern->bind = parse_identifier();
  1575. PatternNode *root_pattern = p_root_pattern == nullptr ? pattern : p_root_pattern;
  1576. if (p_root_pattern != nullptr) {
  1577. if (p_root_pattern->has_bind(pattern->bind->name)) {
  1578. push_error(vformat(R"(Bind variable name "%s" was already used in this pattern.)", pattern->bind->name));
  1579. return nullptr;
  1580. }
  1581. }
  1582. if (current_suite->has_local(pattern->bind->name)) {
  1583. 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));
  1584. return nullptr;
  1585. }
  1586. root_pattern->binds[pattern->bind->name] = pattern->bind;
  1587. } break;
  1588. case GDScriptTokenizer::Token::UNDERSCORE:
  1589. // Wildcard.
  1590. advance();
  1591. pattern->pattern_type = PatternNode::PT_WILDCARD;
  1592. break;
  1593. case GDScriptTokenizer::Token::PERIOD_PERIOD:
  1594. // Rest.
  1595. advance();
  1596. pattern->pattern_type = PatternNode::PT_REST;
  1597. break;
  1598. case GDScriptTokenizer::Token::BRACKET_OPEN: {
  1599. // Array.
  1600. advance();
  1601. pattern->pattern_type = PatternNode::PT_ARRAY;
  1602. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  1603. do {
  1604. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  1605. if (sub_pattern == nullptr) {
  1606. continue;
  1607. }
  1608. if (pattern->rest_used) {
  1609. push_error(R"(The ".." pattern must be the last element in the pattern array.)");
  1610. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  1611. pattern->rest_used = true;
  1612. }
  1613. pattern->array.push_back(sub_pattern);
  1614. } while (match(GDScriptTokenizer::Token::COMMA));
  1615. }
  1616. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" to close the array pattern.)");
  1617. break;
  1618. }
  1619. case GDScriptTokenizer::Token::BRACE_OPEN: {
  1620. // Dictionary.
  1621. advance();
  1622. pattern->pattern_type = PatternNode::PT_DICTIONARY;
  1623. do {
  1624. if (check(GDScriptTokenizer::Token::BRACE_CLOSE) || is_at_end()) {
  1625. break;
  1626. }
  1627. if (match(GDScriptTokenizer::Token::PERIOD_PERIOD)) {
  1628. // Rest.
  1629. if (pattern->rest_used) {
  1630. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  1631. } else {
  1632. PatternNode *sub_pattern = alloc_node<PatternNode>();
  1633. sub_pattern->pattern_type = PatternNode::PT_REST;
  1634. pattern->dictionary.push_back({ nullptr, sub_pattern });
  1635. pattern->rest_used = true;
  1636. }
  1637. } else {
  1638. ExpressionNode *key = parse_expression(false);
  1639. if (key == nullptr) {
  1640. push_error(R"(Expected expression as key for dictionary pattern.)");
  1641. }
  1642. if (match(GDScriptTokenizer::Token::COLON)) {
  1643. // Value pattern.
  1644. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  1645. if (sub_pattern == nullptr) {
  1646. continue;
  1647. }
  1648. if (pattern->rest_used) {
  1649. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  1650. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  1651. push_error(R"(The ".." pattern cannot be used as a value.)");
  1652. } else {
  1653. pattern->dictionary.push_back({ key, sub_pattern });
  1654. }
  1655. } else {
  1656. // Key match only.
  1657. pattern->dictionary.push_back({ key, nullptr });
  1658. }
  1659. }
  1660. } while (match(GDScriptTokenizer::Token::COMMA));
  1661. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected "}" to close the dictionary pattern.)");
  1662. break;
  1663. }
  1664. default: {
  1665. // Expression.
  1666. ExpressionNode *expression = parse_expression(false);
  1667. if (expression == nullptr) {
  1668. push_error(R"(Expected expression for match pattern.)");
  1669. return nullptr;
  1670. } else {
  1671. if (expression->type == GDScriptParser::Node::LITERAL) {
  1672. pattern->pattern_type = PatternNode::PT_LITERAL;
  1673. } else {
  1674. pattern->pattern_type = PatternNode::PT_EXPRESSION;
  1675. }
  1676. pattern->expression = expression;
  1677. }
  1678. break;
  1679. }
  1680. }
  1681. return pattern;
  1682. }
  1683. bool GDScriptParser::PatternNode::has_bind(const StringName &p_name) {
  1684. return binds.has(p_name);
  1685. }
  1686. GDScriptParser::IdentifierNode *GDScriptParser::PatternNode::get_bind(const StringName &p_name) {
  1687. return binds[p_name];
  1688. }
  1689. GDScriptParser::WhileNode *GDScriptParser::parse_while() {
  1690. WhileNode *n_while = alloc_node<WhileNode>();
  1691. n_while->condition = parse_expression(false);
  1692. if (n_while->condition == nullptr) {
  1693. push_error(R"(Expected conditional expression after "while".)");
  1694. }
  1695. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "while" condition.)");
  1696. // Save break/continue state.
  1697. bool could_break = can_break;
  1698. bool could_continue = can_continue;
  1699. bool was_continue_match = is_continue_match;
  1700. // Allow break/continue.
  1701. can_break = true;
  1702. can_continue = true;
  1703. is_continue_match = false;
  1704. n_while->loop = parse_suite(R"("while" block)");
  1705. // Reset break/continue state.
  1706. can_break = could_break;
  1707. can_continue = could_continue;
  1708. is_continue_match = was_continue_match;
  1709. return n_while;
  1710. }
  1711. GDScriptParser::ExpressionNode *GDScriptParser::parse_precedence(Precedence p_precedence, bool p_can_assign, bool p_stop_on_assign) {
  1712. // Switch multiline mode on for grouping tokens.
  1713. // Do this early to avoid the tokenizer generating whitespace tokens.
  1714. switch (current.type) {
  1715. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  1716. case GDScriptTokenizer::Token::BRACE_OPEN:
  1717. case GDScriptTokenizer::Token::BRACKET_OPEN:
  1718. push_multiline(true);
  1719. break;
  1720. default:
  1721. break; // Nothing to do.
  1722. }
  1723. // Completion can appear whenever an expression is expected.
  1724. make_completion_context(COMPLETION_IDENTIFIER, nullptr);
  1725. GDScriptTokenizer::Token token = current;
  1726. ParseFunction prefix_rule = get_rule(token.type)->prefix;
  1727. if (prefix_rule == nullptr) {
  1728. // Expected expression. Let the caller give the proper error message.
  1729. return nullptr;
  1730. }
  1731. advance(); // Only consume the token if there's a valid rule.
  1732. ExpressionNode *previous_operand = (this->*prefix_rule)(nullptr, p_can_assign);
  1733. while (p_precedence <= get_rule(current.type)->precedence) {
  1734. if (p_stop_on_assign && current.type == GDScriptTokenizer::Token::EQUAL) {
  1735. return previous_operand;
  1736. }
  1737. // Also switch multiline mode on here for infix operators.
  1738. switch (current.type) {
  1739. // case GDScriptTokenizer::Token::BRACE_OPEN: // Not an infix operator.
  1740. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  1741. case GDScriptTokenizer::Token::BRACKET_OPEN:
  1742. push_multiline(true);
  1743. break;
  1744. default:
  1745. break; // Nothing to do.
  1746. }
  1747. token = advance();
  1748. ParseFunction infix_rule = get_rule(token.type)->infix;
  1749. previous_operand = (this->*infix_rule)(previous_operand, p_can_assign);
  1750. }
  1751. return previous_operand;
  1752. }
  1753. GDScriptParser::ExpressionNode *GDScriptParser::parse_expression(bool p_can_assign, bool p_stop_on_assign) {
  1754. return parse_precedence(PREC_ASSIGNMENT, p_can_assign, p_stop_on_assign);
  1755. }
  1756. GDScriptParser::IdentifierNode *GDScriptParser::parse_identifier() {
  1757. return static_cast<IdentifierNode *>(parse_identifier(nullptr, false));
  1758. }
  1759. GDScriptParser::ExpressionNode *GDScriptParser::parse_identifier(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1760. if (!previous.is_identifier()) {
  1761. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing literal node without literal token.");
  1762. }
  1763. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  1764. identifier->name = previous.get_identifier();
  1765. if (current_suite != nullptr && current_suite->has_local(identifier->name)) {
  1766. const SuiteNode::Local &declaration = current_suite->get_local(identifier->name);
  1767. identifier->source_function = declaration.source_function;
  1768. switch (declaration.type) {
  1769. case SuiteNode::Local::CONSTANT:
  1770. identifier->source = IdentifierNode::LOCAL_CONSTANT;
  1771. identifier->constant_source = declaration.constant;
  1772. declaration.constant->usages++;
  1773. break;
  1774. case SuiteNode::Local::VARIABLE:
  1775. identifier->source = IdentifierNode::LOCAL_VARIABLE;
  1776. identifier->variable_source = declaration.variable;
  1777. declaration.variable->usages++;
  1778. break;
  1779. case SuiteNode::Local::PARAMETER:
  1780. identifier->source = IdentifierNode::FUNCTION_PARAMETER;
  1781. identifier->parameter_source = declaration.parameter;
  1782. declaration.parameter->usages++;
  1783. break;
  1784. case SuiteNode::Local::FOR_VARIABLE:
  1785. identifier->source = IdentifierNode::LOCAL_ITERATOR;
  1786. identifier->bind_source = declaration.bind;
  1787. declaration.bind->usages++;
  1788. break;
  1789. case SuiteNode::Local::PATTERN_BIND:
  1790. identifier->source = IdentifierNode::LOCAL_BIND;
  1791. identifier->bind_source = declaration.bind;
  1792. declaration.bind->usages++;
  1793. break;
  1794. case SuiteNode::Local::UNDEFINED:
  1795. ERR_FAIL_V_MSG(nullptr, "Undefined local found.");
  1796. }
  1797. }
  1798. return identifier;
  1799. }
  1800. GDScriptParser::LiteralNode *GDScriptParser::parse_literal() {
  1801. return static_cast<LiteralNode *>(parse_literal(nullptr, false));
  1802. }
  1803. GDScriptParser::ExpressionNode *GDScriptParser::parse_literal(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1804. if (previous.type != GDScriptTokenizer::Token::LITERAL) {
  1805. push_error("Parser bug: parsing literal node without literal token.");
  1806. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing literal node without literal token.");
  1807. }
  1808. LiteralNode *literal = alloc_node<LiteralNode>();
  1809. literal->value = previous.literal;
  1810. return literal;
  1811. }
  1812. GDScriptParser::ExpressionNode *GDScriptParser::parse_self(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1813. if (current_function && current_function->is_static) {
  1814. push_error(R"(Cannot use "self" inside a static function.)");
  1815. }
  1816. if (in_lambda) {
  1817. push_error(R"(Cannot use "self" inside a lambda.)");
  1818. }
  1819. SelfNode *self = alloc_node<SelfNode>();
  1820. self->current_class = current_class;
  1821. return self;
  1822. }
  1823. GDScriptParser::ExpressionNode *GDScriptParser::parse_builtin_constant(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1824. GDScriptTokenizer::Token::Type op_type = previous.type;
  1825. LiteralNode *constant = alloc_node<LiteralNode>();
  1826. switch (op_type) {
  1827. case GDScriptTokenizer::Token::CONST_PI:
  1828. constant->value = Math_PI;
  1829. break;
  1830. case GDScriptTokenizer::Token::CONST_TAU:
  1831. constant->value = Math_TAU;
  1832. break;
  1833. case GDScriptTokenizer::Token::CONST_INF:
  1834. constant->value = INFINITY;
  1835. break;
  1836. case GDScriptTokenizer::Token::CONST_NAN:
  1837. constant->value = NAN;
  1838. break;
  1839. default:
  1840. return nullptr; // Unreachable.
  1841. }
  1842. return constant;
  1843. }
  1844. GDScriptParser::ExpressionNode *GDScriptParser::parse_unary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1845. GDScriptTokenizer::Token::Type op_type = previous.type;
  1846. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  1847. switch (op_type) {
  1848. case GDScriptTokenizer::Token::MINUS:
  1849. operation->operation = UnaryOpNode::OP_NEGATIVE;
  1850. operation->variant_op = Variant::OP_NEGATE;
  1851. operation->operand = parse_precedence(PREC_SIGN, false);
  1852. if (operation->operand == nullptr) {
  1853. push_error(R"(Expected expression after "-" operator.)");
  1854. }
  1855. break;
  1856. case GDScriptTokenizer::Token::PLUS:
  1857. operation->operation = UnaryOpNode::OP_POSITIVE;
  1858. operation->variant_op = Variant::OP_POSITIVE;
  1859. operation->operand = parse_precedence(PREC_SIGN, false);
  1860. if (operation->operand == nullptr) {
  1861. push_error(R"(Expected expression after "+" operator.)");
  1862. }
  1863. break;
  1864. case GDScriptTokenizer::Token::TILDE:
  1865. operation->operation = UnaryOpNode::OP_COMPLEMENT;
  1866. operation->variant_op = Variant::OP_BIT_NEGATE;
  1867. operation->operand = parse_precedence(PREC_BIT_NOT, false);
  1868. if (operation->operand == nullptr) {
  1869. push_error(R"(Expected expression after "~" operator.)");
  1870. }
  1871. break;
  1872. case GDScriptTokenizer::Token::NOT:
  1873. case GDScriptTokenizer::Token::BANG:
  1874. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  1875. operation->variant_op = Variant::OP_NOT;
  1876. operation->operand = parse_precedence(PREC_LOGIC_NOT, false);
  1877. if (operation->operand == nullptr) {
  1878. push_error(vformat(R"(Expected expression after "%s" operator.)", op_type == GDScriptTokenizer::Token::NOT ? "not" : "!"));
  1879. }
  1880. break;
  1881. default:
  1882. return nullptr; // Unreachable.
  1883. }
  1884. return operation;
  1885. }
  1886. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_not_in_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1887. // check that NOT is followed by IN by consuming it before calling parse_binary_operator which will only receive a plain IN
  1888. consume(GDScriptTokenizer::Token::IN, R"(Expected "in" after "not" in content-test operator.)");
  1889. ExpressionNode *in_operation = parse_binary_operator(p_previous_operand, p_can_assign);
  1890. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  1891. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  1892. operation->variant_op = Variant::OP_NOT;
  1893. operation->operand = in_operation;
  1894. return operation;
  1895. }
  1896. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1897. GDScriptTokenizer::Token op = previous;
  1898. BinaryOpNode *operation = alloc_node<BinaryOpNode>();
  1899. Precedence precedence = (Precedence)(get_rule(op.type)->precedence + 1);
  1900. operation->left_operand = p_previous_operand;
  1901. operation->right_operand = parse_precedence(precedence, false);
  1902. if (operation->right_operand == nullptr) {
  1903. push_error(vformat(R"(Expected expression after "%s" operator.")", op.get_name()));
  1904. }
  1905. // TODO: Also for unary, ternary, and assignment.
  1906. switch (op.type) {
  1907. case GDScriptTokenizer::Token::PLUS:
  1908. operation->operation = BinaryOpNode::OP_ADDITION;
  1909. operation->variant_op = Variant::OP_ADD;
  1910. break;
  1911. case GDScriptTokenizer::Token::MINUS:
  1912. operation->operation = BinaryOpNode::OP_SUBTRACTION;
  1913. operation->variant_op = Variant::OP_SUBTRACT;
  1914. break;
  1915. case GDScriptTokenizer::Token::STAR:
  1916. operation->operation = BinaryOpNode::OP_MULTIPLICATION;
  1917. operation->variant_op = Variant::OP_MULTIPLY;
  1918. break;
  1919. case GDScriptTokenizer::Token::SLASH:
  1920. operation->operation = BinaryOpNode::OP_DIVISION;
  1921. operation->variant_op = Variant::OP_DIVIDE;
  1922. break;
  1923. case GDScriptTokenizer::Token::PERCENT:
  1924. operation->operation = BinaryOpNode::OP_MODULO;
  1925. operation->variant_op = Variant::OP_MODULE;
  1926. break;
  1927. case GDScriptTokenizer::Token::LESS_LESS:
  1928. operation->operation = BinaryOpNode::OP_BIT_LEFT_SHIFT;
  1929. operation->variant_op = Variant::OP_SHIFT_LEFT;
  1930. break;
  1931. case GDScriptTokenizer::Token::GREATER_GREATER:
  1932. operation->operation = BinaryOpNode::OP_BIT_RIGHT_SHIFT;
  1933. operation->variant_op = Variant::OP_SHIFT_RIGHT;
  1934. break;
  1935. case GDScriptTokenizer::Token::AMPERSAND:
  1936. operation->operation = BinaryOpNode::OP_BIT_AND;
  1937. operation->variant_op = Variant::OP_BIT_AND;
  1938. break;
  1939. case GDScriptTokenizer::Token::PIPE:
  1940. operation->operation = BinaryOpNode::OP_BIT_OR;
  1941. operation->variant_op = Variant::OP_BIT_OR;
  1942. break;
  1943. case GDScriptTokenizer::Token::CARET:
  1944. operation->operation = BinaryOpNode::OP_BIT_XOR;
  1945. operation->variant_op = Variant::OP_BIT_XOR;
  1946. break;
  1947. case GDScriptTokenizer::Token::AND:
  1948. case GDScriptTokenizer::Token::AMPERSAND_AMPERSAND:
  1949. operation->operation = BinaryOpNode::OP_LOGIC_AND;
  1950. operation->variant_op = Variant::OP_AND;
  1951. break;
  1952. case GDScriptTokenizer::Token::OR:
  1953. case GDScriptTokenizer::Token::PIPE_PIPE:
  1954. operation->operation = BinaryOpNode::OP_LOGIC_OR;
  1955. operation->variant_op = Variant::OP_OR;
  1956. break;
  1957. case GDScriptTokenizer::Token::IS:
  1958. operation->operation = BinaryOpNode::OP_TYPE_TEST;
  1959. break;
  1960. case GDScriptTokenizer::Token::IN:
  1961. operation->operation = BinaryOpNode::OP_CONTENT_TEST;
  1962. operation->variant_op = Variant::OP_IN;
  1963. break;
  1964. case GDScriptTokenizer::Token::EQUAL_EQUAL:
  1965. operation->operation = BinaryOpNode::OP_COMP_EQUAL;
  1966. operation->variant_op = Variant::OP_EQUAL;
  1967. break;
  1968. case GDScriptTokenizer::Token::BANG_EQUAL:
  1969. operation->operation = BinaryOpNode::OP_COMP_NOT_EQUAL;
  1970. operation->variant_op = Variant::OP_NOT_EQUAL;
  1971. break;
  1972. case GDScriptTokenizer::Token::LESS:
  1973. operation->operation = BinaryOpNode::OP_COMP_LESS;
  1974. operation->variant_op = Variant::OP_LESS;
  1975. break;
  1976. case GDScriptTokenizer::Token::LESS_EQUAL:
  1977. operation->operation = BinaryOpNode::OP_COMP_LESS_EQUAL;
  1978. operation->variant_op = Variant::OP_LESS_EQUAL;
  1979. break;
  1980. case GDScriptTokenizer::Token::GREATER:
  1981. operation->operation = BinaryOpNode::OP_COMP_GREATER;
  1982. operation->variant_op = Variant::OP_GREATER;
  1983. break;
  1984. case GDScriptTokenizer::Token::GREATER_EQUAL:
  1985. operation->operation = BinaryOpNode::OP_COMP_GREATER_EQUAL;
  1986. operation->variant_op = Variant::OP_GREATER_EQUAL;
  1987. break;
  1988. default:
  1989. return nullptr; // Unreachable.
  1990. }
  1991. return operation;
  1992. }
  1993. GDScriptParser::ExpressionNode *GDScriptParser::parse_ternary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1994. // Only one ternary operation exists, so no abstraction here.
  1995. TernaryOpNode *operation = alloc_node<TernaryOpNode>();
  1996. operation->true_expr = p_previous_operand;
  1997. operation->condition = parse_precedence(PREC_TERNARY, false);
  1998. if (operation->condition == nullptr) {
  1999. push_error(R"(Expected expression as ternary condition after "if".)");
  2000. }
  2001. consume(GDScriptTokenizer::Token::ELSE, R"(Expected "else" after ternary operator condition.)");
  2002. operation->false_expr = parse_precedence(PREC_TERNARY, false);
  2003. if (operation->false_expr == nullptr) {
  2004. push_error(R"(Expected expression after "else".)");
  2005. }
  2006. return operation;
  2007. }
  2008. GDScriptParser::ExpressionNode *GDScriptParser::parse_assignment(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2009. if (!p_can_assign) {
  2010. push_error("Assignment is not allowed inside an expression.");
  2011. return parse_expression(false); // Return the following expression.
  2012. }
  2013. #ifdef DEBUG_ENABLED
  2014. VariableNode *source_variable = nullptr;
  2015. #endif
  2016. switch (p_previous_operand->type) {
  2017. case Node::IDENTIFIER: {
  2018. #ifdef DEBUG_ENABLED
  2019. // Get source to store assignment count.
  2020. // Also remove one usage since assignment isn't usage.
  2021. IdentifierNode *id = static_cast<IdentifierNode *>(p_previous_operand);
  2022. switch (id->source) {
  2023. case IdentifierNode::LOCAL_VARIABLE:
  2024. source_variable = id->variable_source;
  2025. id->variable_source->usages--;
  2026. break;
  2027. case IdentifierNode::LOCAL_CONSTANT:
  2028. id->constant_source->usages--;
  2029. break;
  2030. case IdentifierNode::FUNCTION_PARAMETER:
  2031. id->parameter_source->usages--;
  2032. break;
  2033. case IdentifierNode::LOCAL_ITERATOR:
  2034. case IdentifierNode::LOCAL_BIND:
  2035. id->bind_source->usages--;
  2036. break;
  2037. default:
  2038. break;
  2039. }
  2040. #endif
  2041. } break;
  2042. case Node::SUBSCRIPT:
  2043. // Okay.
  2044. break;
  2045. default:
  2046. push_error(R"(Only identifier, attribute access, and subscription access can be used as assignment target.)");
  2047. return parse_expression(false); // Return the following expression.
  2048. }
  2049. AssignmentNode *assignment = alloc_node<AssignmentNode>();
  2050. make_completion_context(COMPLETION_ASSIGN, assignment);
  2051. #ifdef DEBUG_ENABLED
  2052. bool has_operator = true;
  2053. #endif
  2054. switch (previous.type) {
  2055. case GDScriptTokenizer::Token::EQUAL:
  2056. assignment->operation = AssignmentNode::OP_NONE;
  2057. assignment->variant_op = Variant::OP_MAX;
  2058. #ifdef DEBUG_ENABLED
  2059. has_operator = false;
  2060. #endif
  2061. break;
  2062. case GDScriptTokenizer::Token::PLUS_EQUAL:
  2063. assignment->operation = AssignmentNode::OP_ADDITION;
  2064. assignment->variant_op = Variant::OP_ADD;
  2065. break;
  2066. case GDScriptTokenizer::Token::MINUS_EQUAL:
  2067. assignment->operation = AssignmentNode::OP_SUBTRACTION;
  2068. assignment->variant_op = Variant::OP_SUBTRACT;
  2069. break;
  2070. case GDScriptTokenizer::Token::STAR_EQUAL:
  2071. assignment->operation = AssignmentNode::OP_MULTIPLICATION;
  2072. assignment->variant_op = Variant::OP_MULTIPLY;
  2073. break;
  2074. case GDScriptTokenizer::Token::SLASH_EQUAL:
  2075. assignment->operation = AssignmentNode::OP_DIVISION;
  2076. assignment->variant_op = Variant::OP_DIVIDE;
  2077. break;
  2078. case GDScriptTokenizer::Token::PERCENT_EQUAL:
  2079. assignment->operation = AssignmentNode::OP_MODULO;
  2080. assignment->variant_op = Variant::OP_MODULE;
  2081. break;
  2082. case GDScriptTokenizer::Token::LESS_LESS_EQUAL:
  2083. assignment->operation = AssignmentNode::OP_BIT_SHIFT_LEFT;
  2084. assignment->variant_op = Variant::OP_SHIFT_LEFT;
  2085. break;
  2086. case GDScriptTokenizer::Token::GREATER_GREATER_EQUAL:
  2087. assignment->operation = AssignmentNode::OP_BIT_SHIFT_RIGHT;
  2088. assignment->variant_op = Variant::OP_SHIFT_RIGHT;
  2089. break;
  2090. case GDScriptTokenizer::Token::AMPERSAND_EQUAL:
  2091. assignment->operation = AssignmentNode::OP_BIT_AND;
  2092. assignment->variant_op = Variant::OP_BIT_AND;
  2093. break;
  2094. case GDScriptTokenizer::Token::PIPE_EQUAL:
  2095. assignment->operation = AssignmentNode::OP_BIT_OR;
  2096. assignment->variant_op = Variant::OP_BIT_OR;
  2097. break;
  2098. case GDScriptTokenizer::Token::CARET_EQUAL:
  2099. assignment->operation = AssignmentNode::OP_BIT_XOR;
  2100. assignment->variant_op = Variant::OP_BIT_XOR;
  2101. break;
  2102. default:
  2103. break; // Unreachable.
  2104. }
  2105. assignment->assignee = p_previous_operand;
  2106. assignment->assigned_value = parse_expression(false);
  2107. if (assignment->assigned_value == nullptr) {
  2108. push_error(R"(Expected an expression after "=".)");
  2109. }
  2110. #ifdef DEBUG_ENABLED
  2111. if (source_variable != nullptr) {
  2112. if (has_operator && source_variable->assignments == 0) {
  2113. push_warning(assignment, GDScriptWarning::UNASSIGNED_VARIABLE_OP_ASSIGN, source_variable->identifier->name);
  2114. }
  2115. source_variable->assignments += 1;
  2116. }
  2117. #endif
  2118. return assignment;
  2119. }
  2120. GDScriptParser::ExpressionNode *GDScriptParser::parse_await(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2121. AwaitNode *await = alloc_node<AwaitNode>();
  2122. ExpressionNode *element = parse_precedence(PREC_AWAIT, false);
  2123. if (element == nullptr) {
  2124. push_error(R"(Expected signal or coroutine after "await".)");
  2125. }
  2126. await->to_await = element;
  2127. if (current_function) { // Might be null in a getter or setter.
  2128. current_function->is_coroutine = true;
  2129. }
  2130. return await;
  2131. }
  2132. GDScriptParser::ExpressionNode *GDScriptParser::parse_array(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2133. ArrayNode *array = alloc_node<ArrayNode>();
  2134. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2135. do {
  2136. if (check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2137. // Allow for trailing comma.
  2138. break;
  2139. }
  2140. ExpressionNode *element = parse_expression(false);
  2141. if (element == nullptr) {
  2142. push_error(R"(Expected expression as array element.)");
  2143. } else {
  2144. array->elements.push_back(element);
  2145. }
  2146. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2147. }
  2148. pop_multiline();
  2149. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after array elements.)");
  2150. return array;
  2151. }
  2152. GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2153. DictionaryNode *dictionary = alloc_node<DictionaryNode>();
  2154. bool decided_style = false;
  2155. if (!check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2156. do {
  2157. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2158. // Allow for trailing comma.
  2159. break;
  2160. }
  2161. // Key.
  2162. ExpressionNode *key = parse_expression(false, true); // Stop on "=" so we can check for Lua table style.
  2163. if (key == nullptr) {
  2164. push_error(R"(Expected expression as dictionary key.)");
  2165. }
  2166. if (!decided_style) {
  2167. switch (current.type) {
  2168. case GDScriptTokenizer::Token::COLON:
  2169. dictionary->style = DictionaryNode::PYTHON_DICT;
  2170. break;
  2171. case GDScriptTokenizer::Token::EQUAL:
  2172. dictionary->style = DictionaryNode::LUA_TABLE;
  2173. break;
  2174. default:
  2175. push_error(R"(Expected ":" or "=" after dictionary key.)");
  2176. break;
  2177. }
  2178. decided_style = true;
  2179. }
  2180. switch (dictionary->style) {
  2181. case DictionaryNode::LUA_TABLE:
  2182. if (key != nullptr && key->type != Node::IDENTIFIER && key->type != Node::LITERAL) {
  2183. push_error("Expected identifier or string as LUA-style dictionary key.");
  2184. advance();
  2185. break;
  2186. }
  2187. if (key != nullptr && key->type == Node::LITERAL && static_cast<LiteralNode *>(key)->value.get_type() != Variant::STRING) {
  2188. push_error("Expected identifier or string as LUA-style dictionary key.");
  2189. advance();
  2190. break;
  2191. }
  2192. if (!match(GDScriptTokenizer::Token::EQUAL)) {
  2193. if (match(GDScriptTokenizer::Token::COLON)) {
  2194. push_error(R"(Expected "=" after dictionary key. Mixing dictionary styles is not allowed.)");
  2195. advance(); // Consume wrong separator anyway.
  2196. } else {
  2197. push_error(R"(Expected "=" after dictionary key.)");
  2198. }
  2199. }
  2200. if (key != nullptr) {
  2201. key->is_constant = true;
  2202. if (key->type == Node::IDENTIFIER) {
  2203. key->reduced_value = static_cast<IdentifierNode *>(key)->name;
  2204. } else if (key->type == Node::LITERAL) {
  2205. key->reduced_value = StringName(static_cast<LiteralNode *>(key)->value.operator String());
  2206. }
  2207. }
  2208. break;
  2209. case DictionaryNode::PYTHON_DICT:
  2210. if (!match(GDScriptTokenizer::Token::COLON)) {
  2211. if (match(GDScriptTokenizer::Token::EQUAL)) {
  2212. push_error(R"(Expected ":" after dictionary key. Mixing dictionary styles is not allowed.)");
  2213. advance(); // Consume wrong separator anyway.
  2214. } else {
  2215. push_error(R"(Expected ":" after dictionary key.)");
  2216. }
  2217. }
  2218. break;
  2219. }
  2220. // Value.
  2221. ExpressionNode *value = parse_expression(false);
  2222. if (value == nullptr) {
  2223. push_error(R"(Expected expression as dictionary value.)");
  2224. }
  2225. if (key != nullptr && value != nullptr) {
  2226. dictionary->elements.push_back({ key, value });
  2227. }
  2228. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2229. }
  2230. pop_multiline();
  2231. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" after dictionary elements.)");
  2232. return dictionary;
  2233. }
  2234. GDScriptParser::ExpressionNode *GDScriptParser::parse_grouping(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2235. ExpressionNode *grouped = parse_expression(false);
  2236. pop_multiline();
  2237. if (grouped == nullptr) {
  2238. push_error(R"(Expected grouping expression.)");
  2239. } else {
  2240. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after grouping expression.)*");
  2241. }
  2242. return grouped;
  2243. }
  2244. GDScriptParser::ExpressionNode *GDScriptParser::parse_attribute(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2245. SubscriptNode *attribute = alloc_node<SubscriptNode>();
  2246. if (for_completion) {
  2247. bool is_builtin = false;
  2248. if (p_previous_operand && p_previous_operand->type == Node::IDENTIFIER) {
  2249. const IdentifierNode *id = static_cast<const IdentifierNode *>(p_previous_operand);
  2250. Variant::Type builtin_type = get_builtin_type(id->name);
  2251. if (builtin_type < Variant::VARIANT_MAX) {
  2252. make_completion_context(COMPLETION_BUILT_IN_TYPE_CONSTANT, builtin_type, true);
  2253. is_builtin = true;
  2254. }
  2255. }
  2256. if (!is_builtin) {
  2257. make_completion_context(COMPLETION_ATTRIBUTE, attribute, -1, true);
  2258. }
  2259. }
  2260. attribute->is_attribute = true;
  2261. attribute->base = p_previous_operand;
  2262. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier after "." for attribute access.)")) {
  2263. return attribute;
  2264. }
  2265. attribute->attribute = parse_identifier();
  2266. return attribute;
  2267. }
  2268. GDScriptParser::ExpressionNode *GDScriptParser::parse_subscript(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2269. SubscriptNode *subscript = alloc_node<SubscriptNode>();
  2270. make_completion_context(COMPLETION_SUBSCRIPT, subscript);
  2271. subscript->base = p_previous_operand;
  2272. subscript->index = parse_expression(false);
  2273. if (subscript->index == nullptr) {
  2274. push_error(R"(Expected expression after "[".)");
  2275. }
  2276. pop_multiline();
  2277. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" after subscription index.)");
  2278. return subscript;
  2279. }
  2280. GDScriptParser::ExpressionNode *GDScriptParser::parse_cast(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2281. CastNode *cast = alloc_node<CastNode>();
  2282. cast->operand = p_previous_operand;
  2283. cast->cast_type = parse_type();
  2284. if (cast->cast_type == nullptr) {
  2285. push_error(R"(Expected type specifier after "as".)");
  2286. return p_previous_operand;
  2287. }
  2288. return cast;
  2289. }
  2290. GDScriptParser::ExpressionNode *GDScriptParser::parse_call(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2291. CallNode *call = alloc_node<CallNode>();
  2292. if (previous.type == GDScriptTokenizer::Token::SUPER) {
  2293. // Super call.
  2294. call->is_super = true;
  2295. push_multiline(true);
  2296. if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  2297. // Implicit call to the parent method of the same name.
  2298. if (current_function == nullptr) {
  2299. push_error(R"(Cannot use implicit "super" call outside of a function.)");
  2300. pop_multiline();
  2301. return nullptr;
  2302. }
  2303. call->function_name = current_function->identifier->name;
  2304. } else {
  2305. consume(GDScriptTokenizer::Token::PERIOD, R"(Expected "." or "(" after "super".)");
  2306. make_completion_context(COMPLETION_SUPER_METHOD, call, true);
  2307. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after ".".)")) {
  2308. pop_multiline();
  2309. return nullptr;
  2310. }
  2311. IdentifierNode *identifier = parse_identifier();
  2312. call->callee = identifier;
  2313. call->function_name = identifier->name;
  2314. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after function name.)");
  2315. }
  2316. } else {
  2317. call->callee = p_previous_operand;
  2318. if (call->callee == nullptr) {
  2319. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2320. } else if (call->callee->type == Node::IDENTIFIER) {
  2321. call->function_name = static_cast<IdentifierNode *>(call->callee)->name;
  2322. make_completion_context(COMPLETION_METHOD, call->callee);
  2323. } else if (call->callee->type == Node::SUBSCRIPT) {
  2324. SubscriptNode *attribute = static_cast<SubscriptNode *>(call->callee);
  2325. if (attribute->is_attribute) {
  2326. if (attribute->attribute) {
  2327. call->function_name = attribute->attribute->name;
  2328. }
  2329. make_completion_context(COMPLETION_ATTRIBUTE_METHOD, call->callee);
  2330. } else {
  2331. // TODO: The analyzer can see if this is actually a Callable and give better error message.
  2332. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2333. }
  2334. } else {
  2335. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2336. }
  2337. }
  2338. // Arguments.
  2339. CompletionType ct = COMPLETION_CALL_ARGUMENTS;
  2340. if (call->function_name == "load") {
  2341. ct = COMPLETION_RESOURCE_PATH;
  2342. }
  2343. push_completion_call(call);
  2344. int argument_index = 0;
  2345. do {
  2346. make_completion_context(ct, call, argument_index++, true);
  2347. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  2348. // Allow for trailing comma.
  2349. break;
  2350. }
  2351. ExpressionNode *argument = parse_expression(false);
  2352. if (argument == nullptr) {
  2353. push_error(R"(Expected expression as the function argument.)");
  2354. } else {
  2355. call->arguments.push_back(argument);
  2356. }
  2357. ct = COMPLETION_CALL_ARGUMENTS;
  2358. } while (match(GDScriptTokenizer::Token::COMMA));
  2359. pop_completion_call();
  2360. pop_multiline();
  2361. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after call arguments.)*");
  2362. return call;
  2363. }
  2364. GDScriptParser::ExpressionNode *GDScriptParser::parse_get_node(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2365. if (match(GDScriptTokenizer::Token::LITERAL)) {
  2366. if (previous.literal.get_type() != Variant::STRING) {
  2367. push_error(R"(Expect node path as string or identifier after "$".)");
  2368. return nullptr;
  2369. }
  2370. GetNodeNode *get_node = alloc_node<GetNodeNode>();
  2371. make_completion_context(COMPLETION_GET_NODE, get_node);
  2372. get_node->string = parse_literal();
  2373. return get_node;
  2374. } else if (current.is_node_name()) {
  2375. GetNodeNode *get_node = alloc_node<GetNodeNode>();
  2376. int chain_position = 0;
  2377. do {
  2378. make_completion_context(COMPLETION_GET_NODE, get_node, chain_position++);
  2379. if (!current.is_node_name()) {
  2380. push_error(R"(Expect node path after "/".)");
  2381. return nullptr;
  2382. }
  2383. advance();
  2384. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  2385. identifier->name = previous.get_identifier();
  2386. get_node->chain.push_back(identifier);
  2387. } while (match(GDScriptTokenizer::Token::SLASH));
  2388. return get_node;
  2389. } else {
  2390. push_error(R"(Expect node path as string or identifier after "$".)");
  2391. return nullptr;
  2392. }
  2393. }
  2394. GDScriptParser::ExpressionNode *GDScriptParser::parse_preload(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2395. PreloadNode *preload = alloc_node<PreloadNode>();
  2396. preload->resolved_path = "<missing path>";
  2397. push_multiline(true);
  2398. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "preload".)");
  2399. make_completion_context(COMPLETION_RESOURCE_PATH, preload);
  2400. push_completion_call(preload);
  2401. preload->path = parse_expression(false);
  2402. if (preload->path == nullptr) {
  2403. push_error(R"(Expected resource path after "(".)");
  2404. }
  2405. pop_completion_call();
  2406. pop_multiline();
  2407. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after preload path.)*");
  2408. return preload;
  2409. }
  2410. GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2411. LambdaNode *lambda = alloc_node<LambdaNode>();
  2412. lambda->parent_function = current_function;
  2413. FunctionNode *function = alloc_node<FunctionNode>();
  2414. function->source_lambda = lambda;
  2415. function->is_static = current_function != nullptr ? current_function->is_static : false;
  2416. if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
  2417. function->identifier = parse_identifier();
  2418. }
  2419. bool multiline_context = multiline_stack.back()->get();
  2420. // Reset the multiline stack since we don't want the multiline mode one in the lambda body.
  2421. push_multiline(false);
  2422. if (multiline_context) {
  2423. tokenizer.push_expression_indented_block();
  2424. }
  2425. push_multiline(true); // For the parameters.
  2426. if (function->identifier) {
  2427. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after lambda name.)");
  2428. } else {
  2429. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after "func".)");
  2430. }
  2431. FunctionNode *previous_function = current_function;
  2432. current_function = function;
  2433. SuiteNode *body = alloc_node<SuiteNode>();
  2434. SuiteNode *previous_suite = current_suite;
  2435. current_suite = body;
  2436. parse_function_signature(function, body, "lambda");
  2437. current_suite = previous_suite;
  2438. bool previous_in_lambda = in_lambda;
  2439. in_lambda = true;
  2440. function->body = parse_suite("lambda declaration", body, true);
  2441. pop_multiline();
  2442. if (multiline_context) {
  2443. // If we're in multiline mode, we want to skip the spurious DEDENT and NEWLINE tokens.
  2444. while (check(GDScriptTokenizer::Token::DEDENT) || check(GDScriptTokenizer::Token::INDENT) || check(GDScriptTokenizer::Token::NEWLINE)) {
  2445. current = tokenizer.scan(); // Not advance() since we don't want to change the previous token.
  2446. }
  2447. tokenizer.pop_expression_indented_block();
  2448. }
  2449. current_function = previous_function;
  2450. in_lambda = previous_in_lambda;
  2451. lambda->function = function;
  2452. return lambda;
  2453. }
  2454. GDScriptParser::ExpressionNode *GDScriptParser::parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2455. // Just for better error messages.
  2456. GDScriptTokenizer::Token::Type invalid = previous.type;
  2457. switch (invalid) {
  2458. case GDScriptTokenizer::Token::QUESTION_MARK:
  2459. push_error(R"(Unexpected "?" in source. If you want a ternary operator, use "truthy_value if true_condition else falsy_value".)");
  2460. break;
  2461. default:
  2462. return nullptr; // Unreachable.
  2463. }
  2464. // Return the previous expression.
  2465. return p_previous_operand;
  2466. }
  2467. GDScriptParser::TypeNode *GDScriptParser::parse_type(bool p_allow_void) {
  2468. TypeNode *type = alloc_node<TypeNode>();
  2469. make_completion_context(p_allow_void ? COMPLETION_TYPE_NAME_OR_VOID : COMPLETION_TYPE_NAME, type);
  2470. if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
  2471. if (match(GDScriptTokenizer::Token::VOID)) {
  2472. if (p_allow_void) {
  2473. TypeNode *void_type = alloc_node<TypeNode>();
  2474. return void_type;
  2475. } else {
  2476. push_error(R"("void" is only allowed for a function return type.)");
  2477. }
  2478. }
  2479. // Leave error message to the caller who knows the context.
  2480. return nullptr;
  2481. }
  2482. IdentifierNode *type_element = parse_identifier();
  2483. type->type_chain.push_back(type_element);
  2484. if (match(GDScriptTokenizer::Token::BRACKET_OPEN)) {
  2485. // Typed collection (like Array[int]).
  2486. type->container_type = parse_type(false); // Don't allow void for array element type.
  2487. if (type->container_type == nullptr) {
  2488. push_error(R"(Expected type for collection after "[".)");
  2489. type = nullptr;
  2490. } else if (type->container_type->container_type != nullptr) {
  2491. push_error("Nested typed collections are not supported.");
  2492. }
  2493. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after collection type.)");
  2494. return type;
  2495. }
  2496. int chain_index = 1;
  2497. while (match(GDScriptTokenizer::Token::PERIOD)) {
  2498. make_completion_context(COMPLETION_TYPE_ATTRIBUTE, type, chain_index++);
  2499. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected inner type name after ".".)")) {
  2500. type_element = parse_identifier();
  2501. type->type_chain.push_back(type_element);
  2502. }
  2503. }
  2504. return type;
  2505. }
  2506. #ifdef TOOLS_ENABLED
  2507. static bool _in_codeblock(String p_line, bool p_already_in, int *r_block_begins = nullptr) {
  2508. int start_block = p_line.rfind("[codeblock]");
  2509. int end_block = p_line.rfind("[/codeblock]");
  2510. if (start_block != -1 && r_block_begins) {
  2511. *r_block_begins = start_block;
  2512. }
  2513. if (p_already_in) {
  2514. if (end_block == -1) {
  2515. return true;
  2516. } else if (start_block == -1) {
  2517. return false;
  2518. } else {
  2519. return start_block > end_block;
  2520. }
  2521. } else {
  2522. if (start_block == -1) {
  2523. return false;
  2524. } else if (end_block == -1) {
  2525. return true;
  2526. } else {
  2527. return start_block > end_block;
  2528. }
  2529. }
  2530. }
  2531. bool GDScriptParser::has_comment(int p_line) {
  2532. return tokenizer.get_comments().has(p_line);
  2533. }
  2534. String GDScriptParser::get_doc_comment(int p_line, bool p_single_line) {
  2535. const Map<int, GDScriptTokenizer::CommentData> &comments = tokenizer.get_comments();
  2536. ERR_FAIL_COND_V(!comments.has(p_line), String());
  2537. if (p_single_line) {
  2538. if (comments[p_line].comment.begins_with("##")) {
  2539. return comments[p_line].comment.trim_prefix("##").strip_edges();
  2540. }
  2541. return "";
  2542. }
  2543. String doc;
  2544. int line = p_line;
  2545. bool in_codeblock = false;
  2546. while (comments.has(line - 1)) {
  2547. if (!comments[line - 1].new_line || !comments[line - 1].comment.begins_with("##")) {
  2548. break;
  2549. }
  2550. line--;
  2551. }
  2552. int codeblock_begins = 0;
  2553. while (comments.has(line)) {
  2554. if (!comments[line].new_line || !comments[line].comment.begins_with("##")) {
  2555. break;
  2556. }
  2557. String doc_line = comments[line].comment.trim_prefix("##");
  2558. in_codeblock = _in_codeblock(doc_line, in_codeblock, &codeblock_begins);
  2559. if (in_codeblock) {
  2560. int i = 0;
  2561. for (; i < codeblock_begins; i++) {
  2562. if (doc_line[i] != ' ') {
  2563. break;
  2564. }
  2565. }
  2566. doc_line = doc_line.substr(i);
  2567. } else {
  2568. doc_line = doc_line.strip_edges();
  2569. }
  2570. String line_join = (in_codeblock) ? "\n" : " ";
  2571. doc = (doc.is_empty()) ? doc_line : doc + line_join + doc_line;
  2572. line++;
  2573. }
  2574. return doc;
  2575. }
  2576. 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) {
  2577. const Map<int, GDScriptTokenizer::CommentData> &comments = tokenizer.get_comments();
  2578. if (!comments.has(p_line)) {
  2579. return;
  2580. }
  2581. ERR_FAIL_COND(p_brief != "" || p_desc != "" || p_tutorials.size() != 0);
  2582. int line = p_line;
  2583. bool in_codeblock = false;
  2584. enum Mode {
  2585. BRIEF,
  2586. DESC,
  2587. TUTORIALS,
  2588. DONE,
  2589. };
  2590. Mode mode = BRIEF;
  2591. if (p_inner_class) {
  2592. while (comments.has(line - 1)) {
  2593. if (!comments[line - 1].new_line || !comments[line - 1].comment.begins_with("##")) {
  2594. break;
  2595. }
  2596. line--;
  2597. }
  2598. }
  2599. int codeblock_begins = 0;
  2600. while (comments.has(line)) {
  2601. if (!comments[line].new_line || !comments[line].comment.begins_with("##")) {
  2602. break;
  2603. }
  2604. String title, link; // For tutorials.
  2605. String doc_line = comments[line++].comment.trim_prefix("##");
  2606. String striped_line = doc_line.strip_edges();
  2607. // Set the read mode.
  2608. if (striped_line.begins_with("@desc:") && p_desc == "") {
  2609. mode = DESC;
  2610. striped_line = striped_line.trim_prefix("@desc:");
  2611. in_codeblock = _in_codeblock(doc_line, in_codeblock);
  2612. } else if (striped_line.begins_with("@tutorial")) {
  2613. int begin_scan = String("@tutorial").length();
  2614. if (begin_scan >= striped_line.length()) {
  2615. continue; // invalid syntax.
  2616. }
  2617. if (striped_line[begin_scan] == ':') { // No title.
  2618. // Syntax: ## @tutorial: https://godotengine.org/ // The title argument is optional.
  2619. title = "";
  2620. link = striped_line.trim_prefix("@tutorial:").strip_edges();
  2621. } else {
  2622. /* Syntax:
  2623. @tutorial ( The Title Here ) : https://the.url/
  2624. ^ open ^ close ^ colon ^ url
  2625. */
  2626. int open_bracket_pos = begin_scan, close_bracket_pos = 0;
  2627. while (open_bracket_pos < striped_line.length() && (striped_line[open_bracket_pos] == ' ' || striped_line[open_bracket_pos] == '\t')) {
  2628. open_bracket_pos++;
  2629. }
  2630. if (open_bracket_pos == striped_line.length() || striped_line[open_bracket_pos++] != '(') {
  2631. continue; // invalid syntax.
  2632. }
  2633. close_bracket_pos = open_bracket_pos;
  2634. while (close_bracket_pos < striped_line.length() && striped_line[close_bracket_pos] != ')') {
  2635. close_bracket_pos++;
  2636. }
  2637. if (close_bracket_pos == striped_line.length()) {
  2638. continue; // invalid syntax.
  2639. }
  2640. int colon_pos = close_bracket_pos + 1;
  2641. while (colon_pos < striped_line.length() && (striped_line[colon_pos] == ' ' || striped_line[colon_pos] == '\t')) {
  2642. colon_pos++;
  2643. }
  2644. if (colon_pos == striped_line.length() || striped_line[colon_pos++] != ':') {
  2645. continue; // invalid syntax.
  2646. }
  2647. title = striped_line.substr(open_bracket_pos, close_bracket_pos - open_bracket_pos).strip_edges();
  2648. link = striped_line.substr(colon_pos).strip_edges();
  2649. }
  2650. mode = TUTORIALS;
  2651. in_codeblock = false;
  2652. } else if (striped_line.is_empty()) {
  2653. continue;
  2654. } else {
  2655. // Tutorial docs are single line, we need a @tag after it.
  2656. if (mode == TUTORIALS) {
  2657. mode = DONE;
  2658. }
  2659. in_codeblock = _in_codeblock(doc_line, in_codeblock, &codeblock_begins);
  2660. }
  2661. if (in_codeblock) {
  2662. int i = 0;
  2663. for (; i < codeblock_begins; i++) {
  2664. if (doc_line[i] != ' ') {
  2665. break;
  2666. }
  2667. }
  2668. doc_line = doc_line.substr(i);
  2669. } else {
  2670. doc_line = striped_line;
  2671. }
  2672. String line_join = (in_codeblock) ? "\n" : " ";
  2673. switch (mode) {
  2674. case BRIEF:
  2675. p_brief = (p_brief.length() == 0) ? doc_line : p_brief + line_join + doc_line;
  2676. break;
  2677. case DESC:
  2678. p_desc = (p_desc.length() == 0) ? doc_line : p_desc + line_join + doc_line;
  2679. break;
  2680. case TUTORIALS:
  2681. p_tutorials.append(Pair<String, String>(title, link));
  2682. break;
  2683. case DONE:
  2684. return;
  2685. }
  2686. }
  2687. }
  2688. #endif // TOOLS_ENABLED
  2689. GDScriptParser::ParseRule *GDScriptParser::get_rule(GDScriptTokenizer::Token::Type p_token_type) {
  2690. // Function table for expression parsing.
  2691. // clang-format destroys the alignment here, so turn off for the table.
  2692. /* clang-format off */
  2693. static ParseRule rules[] = {
  2694. // PREFIX INFIX PRECEDENCE (for infix)
  2695. { nullptr, nullptr, PREC_NONE }, // EMPTY,
  2696. // Basic
  2697. { nullptr, nullptr, PREC_NONE }, // ANNOTATION,
  2698. { &GDScriptParser::parse_identifier, nullptr, PREC_NONE }, // IDENTIFIER,
  2699. { &GDScriptParser::parse_literal, nullptr, PREC_NONE }, // LITERAL,
  2700. // Comparison
  2701. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS,
  2702. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS_EQUAL,
  2703. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER,
  2704. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER_EQUAL,
  2705. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // EQUAL_EQUAL,
  2706. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // BANG_EQUAL,
  2707. // Logical
  2708. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AND,
  2709. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // OR,
  2710. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_not_in_operator, PREC_CONTENT_TEST }, // NOT,
  2711. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AMPERSAND_AMPERSAND,
  2712. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // PIPE_PIPE,
  2713. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // BANG,
  2714. // Bitwise
  2715. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_AND }, // AMPERSAND,
  2716. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_OR }, // PIPE,
  2717. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // TILDE,
  2718. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_XOR }, // CARET,
  2719. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // LESS_LESS,
  2720. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // GREATER_GREATER,
  2721. // Math
  2722. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // PLUS,
  2723. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // MINUS,
  2724. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // STAR,
  2725. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // SLASH,
  2726. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // PERCENT,
  2727. // Assignment
  2728. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // EQUAL,
  2729. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PLUS_EQUAL,
  2730. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // MINUS_EQUAL,
  2731. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_EQUAL,
  2732. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // SLASH_EQUAL,
  2733. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PERCENT_EQUAL,
  2734. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // LESS_LESS_EQUAL,
  2735. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // GREATER_GREATER_EQUAL,
  2736. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // AMPERSAND_EQUAL,
  2737. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PIPE_EQUAL,
  2738. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // CARET_EQUAL,
  2739. // Control flow
  2740. { nullptr, &GDScriptParser::parse_ternary_operator, PREC_TERNARY }, // IF,
  2741. { nullptr, nullptr, PREC_NONE }, // ELIF,
  2742. { nullptr, nullptr, PREC_NONE }, // ELSE,
  2743. { nullptr, nullptr, PREC_NONE }, // FOR,
  2744. { nullptr, nullptr, PREC_NONE }, // WHILE,
  2745. { nullptr, nullptr, PREC_NONE }, // BREAK,
  2746. { nullptr, nullptr, PREC_NONE }, // CONTINUE,
  2747. { nullptr, nullptr, PREC_NONE }, // PASS,
  2748. { nullptr, nullptr, PREC_NONE }, // RETURN,
  2749. { nullptr, nullptr, PREC_NONE }, // MATCH,
  2750. // Keywords
  2751. { nullptr, &GDScriptParser::parse_cast, PREC_CAST }, // AS,
  2752. { nullptr, nullptr, PREC_NONE }, // ASSERT,
  2753. { &GDScriptParser::parse_await, nullptr, PREC_NONE }, // AWAIT,
  2754. { nullptr, nullptr, PREC_NONE }, // BREAKPOINT,
  2755. { nullptr, nullptr, PREC_NONE }, // CLASS,
  2756. { nullptr, nullptr, PREC_NONE }, // CLASS_NAME,
  2757. { nullptr, nullptr, PREC_NONE }, // CONST,
  2758. { nullptr, nullptr, PREC_NONE }, // ENUM,
  2759. { nullptr, nullptr, PREC_NONE }, // EXTENDS,
  2760. { &GDScriptParser::parse_lambda, nullptr, PREC_NONE }, // FUNC,
  2761. { nullptr, &GDScriptParser::parse_binary_operator, PREC_CONTENT_TEST }, // IN,
  2762. { nullptr, &GDScriptParser::parse_binary_operator, PREC_TYPE_TEST }, // IS,
  2763. { nullptr, nullptr, PREC_NONE }, // NAMESPACE,
  2764. { &GDScriptParser::parse_preload, nullptr, PREC_NONE }, // PRELOAD,
  2765. { &GDScriptParser::parse_self, nullptr, PREC_NONE }, // SELF,
  2766. { nullptr, nullptr, PREC_NONE }, // SIGNAL,
  2767. { nullptr, nullptr, PREC_NONE }, // STATIC,
  2768. { &GDScriptParser::parse_call, nullptr, PREC_NONE }, // SUPER,
  2769. { nullptr, nullptr, PREC_NONE }, // TRAIT,
  2770. { nullptr, nullptr, PREC_NONE }, // VAR,
  2771. { nullptr, nullptr, PREC_NONE }, // VOID,
  2772. { nullptr, nullptr, PREC_NONE }, // YIELD,
  2773. // Punctuation
  2774. { &GDScriptParser::parse_array, &GDScriptParser::parse_subscript, PREC_SUBSCRIPT }, // BRACKET_OPEN,
  2775. { nullptr, nullptr, PREC_NONE }, // BRACKET_CLOSE,
  2776. { &GDScriptParser::parse_dictionary, nullptr, PREC_NONE }, // BRACE_OPEN,
  2777. { nullptr, nullptr, PREC_NONE }, // BRACE_CLOSE,
  2778. { &GDScriptParser::parse_grouping, &GDScriptParser::parse_call, PREC_CALL }, // PARENTHESIS_OPEN,
  2779. { nullptr, nullptr, PREC_NONE }, // PARENTHESIS_CLOSE,
  2780. { nullptr, nullptr, PREC_NONE }, // COMMA,
  2781. { nullptr, nullptr, PREC_NONE }, // SEMICOLON,
  2782. { nullptr, &GDScriptParser::parse_attribute, PREC_ATTRIBUTE }, // PERIOD,
  2783. { nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD,
  2784. { nullptr, nullptr, PREC_NONE }, // COLON,
  2785. { &GDScriptParser::parse_get_node, nullptr, PREC_NONE }, // DOLLAR,
  2786. { nullptr, nullptr, PREC_NONE }, // FORWARD_ARROW,
  2787. { nullptr, nullptr, PREC_NONE }, // UNDERSCORE,
  2788. // Whitespace
  2789. { nullptr, nullptr, PREC_NONE }, // NEWLINE,
  2790. { nullptr, nullptr, PREC_NONE }, // INDENT,
  2791. { nullptr, nullptr, PREC_NONE }, // DEDENT,
  2792. // Constants
  2793. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_PI,
  2794. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_TAU,
  2795. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_INF,
  2796. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_NAN,
  2797. // Error message improvement
  2798. { nullptr, nullptr, PREC_NONE }, // VCS_CONFLICT_MARKER,
  2799. { nullptr, nullptr, PREC_NONE }, // BACKTICK,
  2800. { nullptr, &GDScriptParser::parse_invalid_token, PREC_CAST }, // QUESTION_MARK,
  2801. // Special
  2802. { nullptr, nullptr, PREC_NONE }, // ERROR,
  2803. { nullptr, nullptr, PREC_NONE }, // TK_EOF,
  2804. };
  2805. /* clang-format on */
  2806. // Avoid desync.
  2807. static_assert(sizeof(rules) / sizeof(rules[0]) == GDScriptTokenizer::Token::TK_MAX, "Amount of parse rules don't match the amount of token types.");
  2808. // Let's assume this is never invalid, since nothing generates a TK_MAX.
  2809. return &rules[p_token_type];
  2810. }
  2811. bool GDScriptParser::SuiteNode::has_local(const StringName &p_name) const {
  2812. if (locals_indices.has(p_name)) {
  2813. return true;
  2814. }
  2815. if (parent_block != nullptr) {
  2816. return parent_block->has_local(p_name);
  2817. }
  2818. return false;
  2819. }
  2820. const GDScriptParser::SuiteNode::Local &GDScriptParser::SuiteNode::get_local(const StringName &p_name) const {
  2821. if (locals_indices.has(p_name)) {
  2822. return locals[locals_indices[p_name]];
  2823. }
  2824. if (parent_block != nullptr) {
  2825. return parent_block->get_local(p_name);
  2826. }
  2827. return empty;
  2828. }
  2829. bool GDScriptParser::AnnotationNode::apply(GDScriptParser *p_this, Node *p_target) const {
  2830. return (p_this->*(p_this->valid_annotations[name].apply))(this, p_target);
  2831. }
  2832. bool GDScriptParser::AnnotationNode::applies_to(uint32_t p_target_kinds) const {
  2833. return (info->target_kind & p_target_kinds) > 0;
  2834. }
  2835. bool GDScriptParser::validate_annotation_arguments(AnnotationNode *p_annotation) {
  2836. ERR_FAIL_COND_V_MSG(!valid_annotations.has(p_annotation->name), false, vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
  2837. const MethodInfo &info = valid_annotations[p_annotation->name].info;
  2838. if (((info.flags & METHOD_FLAG_VARARG) == 0) && p_annotation->arguments.size() > info.arguments.size()) {
  2839. 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()));
  2840. return false;
  2841. }
  2842. if (p_annotation->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  2843. 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()));
  2844. return false;
  2845. }
  2846. const List<PropertyInfo>::Element *E = info.arguments.front();
  2847. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  2848. ExpressionNode *argument = p_annotation->arguments[i];
  2849. const PropertyInfo &parameter = E->get();
  2850. if (E->next() != nullptr) {
  2851. E = E->next();
  2852. }
  2853. switch (parameter.type) {
  2854. case Variant::STRING:
  2855. case Variant::STRING_NAME:
  2856. case Variant::NODE_PATH:
  2857. // Allow "quote-less strings", as long as they are recognized as identifiers.
  2858. if (argument->type == Node::IDENTIFIER) {
  2859. IdentifierNode *string = static_cast<IdentifierNode *>(argument);
  2860. Callable::CallError error;
  2861. Vector<Variant> args = varray(string->name);
  2862. const Variant *name = args.ptr();
  2863. Variant r;
  2864. Variant::construct(parameter.type, r, &(name), 1, error);
  2865. p_annotation->resolved_arguments.push_back(r);
  2866. if (error.error != Callable::CallError::CALL_OK) {
  2867. push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
  2868. p_annotation->resolved_arguments.remove(p_annotation->resolved_arguments.size() - 1);
  2869. return false;
  2870. }
  2871. break;
  2872. }
  2873. [[fallthrough]];
  2874. default: {
  2875. if (argument->type != Node::LITERAL) {
  2876. push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
  2877. return false;
  2878. }
  2879. Variant value = static_cast<LiteralNode *>(argument)->value;
  2880. if (!Variant::can_convert_strict(value.get_type(), parameter.type)) {
  2881. push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
  2882. return false;
  2883. }
  2884. Callable::CallError error;
  2885. const Variant *args = &value;
  2886. Variant r;
  2887. Variant::construct(parameter.type, r, &(args), 1, error);
  2888. p_annotation->resolved_arguments.push_back(r);
  2889. if (error.error != Callable::CallError::CALL_OK) {
  2890. push_error(vformat(R"(Expected %s as argument %d of annotation "%s").)", Variant::get_type_name(parameter.type), i + 1, p_annotation->name));
  2891. p_annotation->resolved_arguments.remove(p_annotation->resolved_arguments.size() - 1);
  2892. return false;
  2893. }
  2894. break;
  2895. }
  2896. }
  2897. }
  2898. return true;
  2899. }
  2900. bool GDScriptParser::tool_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  2901. this->_is_tool = true;
  2902. return true;
  2903. }
  2904. bool GDScriptParser::icon_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  2905. ERR_FAIL_COND_V_MSG(p_node->type != Node::CLASS, false, R"("@icon" annotation can only be applied to classes.)");
  2906. ClassNode *p_class = static_cast<ClassNode *>(p_node);
  2907. p_class->icon_path = p_annotation->resolved_arguments[0];
  2908. return true;
  2909. }
  2910. bool GDScriptParser::onready_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  2911. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, R"("@onready" annotation can only be applied to class variables.)");
  2912. VariableNode *variable = static_cast<VariableNode *>(p_node);
  2913. if (variable->onready) {
  2914. push_error(R"("@onready" annotation can only be used once per variable.)");
  2915. return false;
  2916. }
  2917. variable->onready = true;
  2918. current_class->onready_used = true;
  2919. return true;
  2920. }
  2921. template <PropertyHint t_hint, Variant::Type t_type>
  2922. bool GDScriptParser::export_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  2923. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  2924. VariableNode *variable = static_cast<VariableNode *>(p_node);
  2925. if (variable->exported) {
  2926. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  2927. return false;
  2928. }
  2929. variable->exported = true;
  2930. variable->export_info.type = t_type;
  2931. variable->export_info.hint = t_hint;
  2932. String hint_string;
  2933. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  2934. if (i > 0) {
  2935. hint_string += ",";
  2936. }
  2937. hint_string += String(p_annotation->resolved_arguments[i]);
  2938. }
  2939. variable->export_info.hint_string = hint_string;
  2940. // This is called after tne analyzer is done finding the type, so this should be set here.
  2941. DataType export_type = variable->get_datatype();
  2942. if (p_annotation->name == "@export") {
  2943. if (variable->datatype_specifier == nullptr && variable->initializer == nullptr) {
  2944. push_error(R"(Cannot use simple "@export" annotation with variable without type or initializer, since type can't be inferred.)", p_annotation);
  2945. return false;
  2946. }
  2947. bool is_array = false;
  2948. if (export_type.builtin_type == Variant::ARRAY && export_type.has_container_element_type()) {
  2949. export_type = export_type.get_container_element_type(); // Use inner type for.
  2950. is_array = true;
  2951. }
  2952. if (export_type.is_variant() || export_type.has_no_type()) {
  2953. push_error(R"(Cannot use simple "@export" annotation because the type of the initialized value can't be inferred.)", p_annotation);
  2954. return false;
  2955. }
  2956. switch (export_type.kind) {
  2957. case GDScriptParser::DataType::BUILTIN:
  2958. variable->export_info.type = export_type.builtin_type;
  2959. variable->export_info.hint = PROPERTY_HINT_NONE;
  2960. variable->export_info.hint_string = Variant::get_type_name(export_type.builtin_type);
  2961. break;
  2962. case GDScriptParser::DataType::NATIVE:
  2963. if (ClassDB::is_parent_class(export_type.native_type, "Resource")) {
  2964. variable->export_info.type = Variant::OBJECT;
  2965. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  2966. variable->export_info.hint_string = export_type.native_type;
  2967. } else {
  2968. push_error(R"(Export type can only be built-in, a resource, or an enum.)", variable);
  2969. return false;
  2970. }
  2971. break;
  2972. case GDScriptParser::DataType::ENUM: {
  2973. variable->export_info.type = Variant::INT;
  2974. variable->export_info.hint = PROPERTY_HINT_ENUM;
  2975. String enum_hint_string;
  2976. for (const Map<StringName, int>::Element *E = export_type.enum_values.front(); E; E = E->next()) {
  2977. enum_hint_string += E->key().operator String().camelcase_to_underscore(true).capitalize().xml_escape();
  2978. enum_hint_string += ":";
  2979. enum_hint_string += String::num_int64(E->get()).xml_escape();
  2980. if (E->next()) {
  2981. enum_hint_string += ",";
  2982. }
  2983. }
  2984. variable->export_info.hint_string = enum_hint_string;
  2985. } break;
  2986. default:
  2987. // TODO: Allow custom user resources.
  2988. push_error(R"(Export type can only be built-in, a resource, or an enum.)", variable);
  2989. break;
  2990. }
  2991. if (is_array) {
  2992. String hint_prefix = itos(variable->export_info.type);
  2993. if (variable->export_info.hint) {
  2994. hint_prefix += "/" + itos(variable->export_info.hint);
  2995. }
  2996. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  2997. variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
  2998. variable->export_info.type = Variant::ARRAY;
  2999. }
  3000. } else {
  3001. // Validate variable type with export.
  3002. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != t_type)) {
  3003. // Allow float/int conversion.
  3004. if ((t_type != Variant::FLOAT || export_type.builtin_type != Variant::INT) && (t_type != Variant::INT || export_type.builtin_type != Variant::FLOAT)) {
  3005. 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);
  3006. return false;
  3007. }
  3008. }
  3009. }
  3010. return true;
  3011. }
  3012. bool GDScriptParser::warning_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  3013. ERR_FAIL_V_MSG(false, "Not implemented.");
  3014. }
  3015. template <Multiplayer::RPCMode t_mode>
  3016. bool GDScriptParser::network_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  3017. 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));
  3018. Multiplayer::RPCConfig rpc_config;
  3019. rpc_config.rpc_mode = t_mode;
  3020. if (p_annotation->resolved_arguments.size()) {
  3021. int last = p_annotation->resolved_arguments.size() - 1;
  3022. if (p_annotation->resolved_arguments[last].get_type() == Variant::INT) {
  3023. rpc_config.channel = p_annotation->resolved_arguments[last].operator int();
  3024. last -= 1;
  3025. }
  3026. if (last > 3) {
  3027. 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);
  3028. return false;
  3029. }
  3030. for (int i = last; i >= 0; i--) {
  3031. String mode = p_annotation->resolved_arguments[i].operator String();
  3032. if (mode == "any") {
  3033. rpc_config.rpc_mode = Multiplayer::RPC_MODE_ANY;
  3034. } else if (mode == "auth") {
  3035. rpc_config.rpc_mode = Multiplayer::RPC_MODE_AUTHORITY;
  3036. } else if (mode == "sync") {
  3037. rpc_config.sync = true;
  3038. } else if (mode == "nosync") {
  3039. rpc_config.sync = false;
  3040. } else if (mode == "reliable") {
  3041. rpc_config.transfer_mode = Multiplayer::TRANSFER_MODE_RELIABLE;
  3042. } else if (mode == "unreliable") {
  3043. rpc_config.transfer_mode = Multiplayer::TRANSFER_MODE_UNRELIABLE;
  3044. } else if (mode == "ordered") {
  3045. rpc_config.transfer_mode = Multiplayer::TRANSFER_MODE_ORDERED;
  3046. } else {
  3047. push_error(R"(Invalid RPC argument. Must be one of: 'sync'/'nosync' (local calls), 'any'/'auth' (permission), 'reliable'/'unreliable'/'ordered' (transfer mode).)", p_annotation);
  3048. }
  3049. }
  3050. }
  3051. switch (p_node->type) {
  3052. case Node::FUNCTION: {
  3053. FunctionNode *function = static_cast<FunctionNode *>(p_node);
  3054. if (function->rpc_config.rpc_mode != Multiplayer::RPC_MODE_DISABLED) {
  3055. push_error(R"(RPC annotations can only be used once per function.)", p_annotation);
  3056. return false;
  3057. }
  3058. function->rpc_config = rpc_config;
  3059. break;
  3060. }
  3061. default:
  3062. return false; // Unreachable.
  3063. }
  3064. return true;
  3065. }
  3066. GDScriptParser::DataType GDScriptParser::SuiteNode::Local::get_datatype() const {
  3067. switch (type) {
  3068. case CONSTANT:
  3069. return constant->get_datatype();
  3070. case VARIABLE:
  3071. return variable->get_datatype();
  3072. case PARAMETER:
  3073. return parameter->get_datatype();
  3074. case FOR_VARIABLE:
  3075. case PATTERN_BIND:
  3076. return bind->get_datatype();
  3077. case UNDEFINED:
  3078. return DataType();
  3079. }
  3080. return DataType();
  3081. }
  3082. String GDScriptParser::SuiteNode::Local::get_name() const {
  3083. String name;
  3084. switch (type) {
  3085. case SuiteNode::Local::PARAMETER:
  3086. name = "parameter";
  3087. break;
  3088. case SuiteNode::Local::CONSTANT:
  3089. name = "constant";
  3090. break;
  3091. case SuiteNode::Local::VARIABLE:
  3092. name = "variable";
  3093. break;
  3094. case SuiteNode::Local::FOR_VARIABLE:
  3095. name = "for loop iterator";
  3096. break;
  3097. case SuiteNode::Local::PATTERN_BIND:
  3098. name = "pattern_bind";
  3099. break;
  3100. case SuiteNode::Local::UNDEFINED:
  3101. name = "<undefined>";
  3102. break;
  3103. }
  3104. return name;
  3105. }
  3106. String GDScriptParser::DataType::to_string() const {
  3107. switch (kind) {
  3108. case VARIANT:
  3109. return "Variant";
  3110. case BUILTIN:
  3111. if (builtin_type == Variant::NIL) {
  3112. return "null";
  3113. }
  3114. if (builtin_type == Variant::ARRAY && has_container_element_type()) {
  3115. return vformat("Array[%s]", container_element_type->to_string());
  3116. }
  3117. return Variant::get_type_name(builtin_type);
  3118. case NATIVE:
  3119. if (is_meta_type) {
  3120. return GDScriptNativeClass::get_class_static();
  3121. }
  3122. return native_type.operator String();
  3123. case CLASS:
  3124. if (is_meta_type) {
  3125. return GDScript::get_class_static();
  3126. }
  3127. if (class_type->identifier != nullptr) {
  3128. return class_type->identifier->name.operator String();
  3129. }
  3130. return class_type->fqcn;
  3131. case SCRIPT: {
  3132. if (is_meta_type) {
  3133. return script_type->get_class_name().operator String();
  3134. }
  3135. String name = script_type->get_name();
  3136. if (!name.is_empty()) {
  3137. return name;
  3138. }
  3139. name = script_path;
  3140. if (!name.is_empty()) {
  3141. return name;
  3142. }
  3143. return native_type.operator String();
  3144. }
  3145. case ENUM:
  3146. return enum_type.operator String() + " (enum)";
  3147. case ENUM_VALUE:
  3148. return enum_type.operator String() + " (enum value)";
  3149. case UNRESOLVED:
  3150. return "<unresolved type>";
  3151. }
  3152. ERR_FAIL_V_MSG("<unresolved type", "Kind set outside the enum range.");
  3153. }
  3154. static Variant::Type _variant_type_to_typed_array_element_type(Variant::Type p_type) {
  3155. switch (p_type) {
  3156. case Variant::PACKED_BYTE_ARRAY:
  3157. case Variant::PACKED_INT32_ARRAY:
  3158. case Variant::PACKED_INT64_ARRAY:
  3159. return Variant::INT;
  3160. case Variant::PACKED_FLOAT32_ARRAY:
  3161. case Variant::PACKED_FLOAT64_ARRAY:
  3162. return Variant::FLOAT;
  3163. case Variant::PACKED_STRING_ARRAY:
  3164. return Variant::STRING;
  3165. case Variant::PACKED_VECTOR2_ARRAY:
  3166. return Variant::VECTOR2;
  3167. case Variant::PACKED_VECTOR3_ARRAY:
  3168. return Variant::VECTOR3;
  3169. case Variant::PACKED_COLOR_ARRAY:
  3170. return Variant::COLOR;
  3171. default:
  3172. return Variant::NIL;
  3173. }
  3174. }
  3175. bool GDScriptParser::DataType::is_typed_container_type() const {
  3176. return kind == GDScriptParser::DataType::BUILTIN && _variant_type_to_typed_array_element_type(builtin_type) != Variant::NIL;
  3177. }
  3178. GDScriptParser::DataType GDScriptParser::DataType::get_typed_container_type() const {
  3179. GDScriptParser::DataType type;
  3180. type.kind = GDScriptParser::DataType::BUILTIN;
  3181. type.builtin_type = _variant_type_to_typed_array_element_type(builtin_type);
  3182. return type;
  3183. }
  3184. /*---------- PRETTY PRINT FOR DEBUG ----------*/
  3185. #ifdef DEBUG_ENABLED
  3186. void GDScriptParser::TreePrinter::increase_indent() {
  3187. indent_level++;
  3188. indent = "";
  3189. for (int i = 0; i < indent_level * 4; i++) {
  3190. if (i % 4 == 0) {
  3191. indent += "|";
  3192. } else {
  3193. indent += " ";
  3194. }
  3195. }
  3196. }
  3197. void GDScriptParser::TreePrinter::decrease_indent() {
  3198. indent_level--;
  3199. indent = "";
  3200. for (int i = 0; i < indent_level * 4; i++) {
  3201. if (i % 4 == 0) {
  3202. indent += "|";
  3203. } else {
  3204. indent += " ";
  3205. }
  3206. }
  3207. }
  3208. void GDScriptParser::TreePrinter::push_line(const String &p_line) {
  3209. if (!p_line.is_empty()) {
  3210. push_text(p_line);
  3211. }
  3212. printed += "\n";
  3213. pending_indent = true;
  3214. }
  3215. void GDScriptParser::TreePrinter::push_text(const String &p_text) {
  3216. if (pending_indent) {
  3217. printed += indent;
  3218. pending_indent = false;
  3219. }
  3220. printed += p_text;
  3221. }
  3222. void GDScriptParser::TreePrinter::print_annotation(const AnnotationNode *p_annotation) {
  3223. push_text(p_annotation->name);
  3224. push_text(" (");
  3225. for (int i = 0; i < p_annotation->arguments.size(); i++) {
  3226. if (i > 0) {
  3227. push_text(" , ");
  3228. }
  3229. print_expression(p_annotation->arguments[i]);
  3230. }
  3231. push_line(")");
  3232. }
  3233. void GDScriptParser::TreePrinter::print_array(ArrayNode *p_array) {
  3234. push_text("[ ");
  3235. for (int i = 0; i < p_array->elements.size(); i++) {
  3236. if (i > 0) {
  3237. push_text(" , ");
  3238. }
  3239. print_expression(p_array->elements[i]);
  3240. }
  3241. push_text(" ]");
  3242. }
  3243. void GDScriptParser::TreePrinter::print_assert(AssertNode *p_assert) {
  3244. push_text("Assert ( ");
  3245. print_expression(p_assert->condition);
  3246. push_line(" )");
  3247. }
  3248. void GDScriptParser::TreePrinter::print_assignment(AssignmentNode *p_assignment) {
  3249. switch (p_assignment->assignee->type) {
  3250. case Node::IDENTIFIER:
  3251. print_identifier(static_cast<IdentifierNode *>(p_assignment->assignee));
  3252. break;
  3253. case Node::SUBSCRIPT:
  3254. print_subscript(static_cast<SubscriptNode *>(p_assignment->assignee));
  3255. break;
  3256. default:
  3257. break; // Unreachable.
  3258. }
  3259. push_text(" ");
  3260. switch (p_assignment->operation) {
  3261. case AssignmentNode::OP_ADDITION:
  3262. push_text("+");
  3263. break;
  3264. case AssignmentNode::OP_SUBTRACTION:
  3265. push_text("-");
  3266. break;
  3267. case AssignmentNode::OP_MULTIPLICATION:
  3268. push_text("*");
  3269. break;
  3270. case AssignmentNode::OP_DIVISION:
  3271. push_text("/");
  3272. break;
  3273. case AssignmentNode::OP_MODULO:
  3274. push_text("%");
  3275. break;
  3276. case AssignmentNode::OP_BIT_SHIFT_LEFT:
  3277. push_text("<<");
  3278. break;
  3279. case AssignmentNode::OP_BIT_SHIFT_RIGHT:
  3280. push_text(">>");
  3281. break;
  3282. case AssignmentNode::OP_BIT_AND:
  3283. push_text("&");
  3284. break;
  3285. case AssignmentNode::OP_BIT_OR:
  3286. push_text("|");
  3287. break;
  3288. case AssignmentNode::OP_BIT_XOR:
  3289. push_text("^");
  3290. break;
  3291. case AssignmentNode::OP_NONE:
  3292. break;
  3293. }
  3294. push_text("= ");
  3295. print_expression(p_assignment->assigned_value);
  3296. push_line();
  3297. }
  3298. void GDScriptParser::TreePrinter::print_await(AwaitNode *p_await) {
  3299. push_text("Await ");
  3300. print_expression(p_await->to_await);
  3301. }
  3302. void GDScriptParser::TreePrinter::print_binary_op(BinaryOpNode *p_binary_op) {
  3303. // Surround in parenthesis for disambiguation.
  3304. push_text("(");
  3305. print_expression(p_binary_op->left_operand);
  3306. switch (p_binary_op->operation) {
  3307. case BinaryOpNode::OP_ADDITION:
  3308. push_text(" + ");
  3309. break;
  3310. case BinaryOpNode::OP_SUBTRACTION:
  3311. push_text(" - ");
  3312. break;
  3313. case BinaryOpNode::OP_MULTIPLICATION:
  3314. push_text(" * ");
  3315. break;
  3316. case BinaryOpNode::OP_DIVISION:
  3317. push_text(" / ");
  3318. break;
  3319. case BinaryOpNode::OP_MODULO:
  3320. push_text(" % ");
  3321. break;
  3322. case BinaryOpNode::OP_BIT_LEFT_SHIFT:
  3323. push_text(" << ");
  3324. break;
  3325. case BinaryOpNode::OP_BIT_RIGHT_SHIFT:
  3326. push_text(" >> ");
  3327. break;
  3328. case BinaryOpNode::OP_BIT_AND:
  3329. push_text(" & ");
  3330. break;
  3331. case BinaryOpNode::OP_BIT_OR:
  3332. push_text(" | ");
  3333. break;
  3334. case BinaryOpNode::OP_BIT_XOR:
  3335. push_text(" ^ ");
  3336. break;
  3337. case BinaryOpNode::OP_LOGIC_AND:
  3338. push_text(" AND ");
  3339. break;
  3340. case BinaryOpNode::OP_LOGIC_OR:
  3341. push_text(" OR ");
  3342. break;
  3343. case BinaryOpNode::OP_TYPE_TEST:
  3344. push_text(" IS ");
  3345. break;
  3346. case BinaryOpNode::OP_CONTENT_TEST:
  3347. push_text(" IN ");
  3348. break;
  3349. case BinaryOpNode::OP_COMP_EQUAL:
  3350. push_text(" == ");
  3351. break;
  3352. case BinaryOpNode::OP_COMP_NOT_EQUAL:
  3353. push_text(" != ");
  3354. break;
  3355. case BinaryOpNode::OP_COMP_LESS:
  3356. push_text(" < ");
  3357. break;
  3358. case BinaryOpNode::OP_COMP_LESS_EQUAL:
  3359. push_text(" <= ");
  3360. break;
  3361. case BinaryOpNode::OP_COMP_GREATER:
  3362. push_text(" > ");
  3363. break;
  3364. case BinaryOpNode::OP_COMP_GREATER_EQUAL:
  3365. push_text(" >= ");
  3366. break;
  3367. }
  3368. print_expression(p_binary_op->right_operand);
  3369. // Surround in parenthesis for disambiguation.
  3370. push_text(")");
  3371. }
  3372. void GDScriptParser::TreePrinter::print_call(CallNode *p_call) {
  3373. if (p_call->is_super) {
  3374. push_text("super");
  3375. if (p_call->callee != nullptr) {
  3376. push_text(".");
  3377. print_expression(p_call->callee);
  3378. }
  3379. } else {
  3380. print_expression(p_call->callee);
  3381. }
  3382. push_text("( ");
  3383. for (int i = 0; i < p_call->arguments.size(); i++) {
  3384. if (i > 0) {
  3385. push_text(" , ");
  3386. }
  3387. print_expression(p_call->arguments[i]);
  3388. }
  3389. push_text(" )");
  3390. }
  3391. void GDScriptParser::TreePrinter::print_cast(CastNode *p_cast) {
  3392. print_expression(p_cast->operand);
  3393. push_text(" AS ");
  3394. print_type(p_cast->cast_type);
  3395. }
  3396. void GDScriptParser::TreePrinter::print_class(ClassNode *p_class) {
  3397. push_text("Class ");
  3398. if (p_class->identifier == nullptr) {
  3399. push_text("<unnamed>");
  3400. } else {
  3401. print_identifier(p_class->identifier);
  3402. }
  3403. if (p_class->extends_used) {
  3404. bool first = true;
  3405. push_text(" Extends ");
  3406. if (!p_class->extends_path.is_empty()) {
  3407. push_text(vformat(R"("%s")", p_class->extends_path));
  3408. first = false;
  3409. }
  3410. for (int i = 0; i < p_class->extends.size(); i++) {
  3411. if (!first) {
  3412. push_text(".");
  3413. } else {
  3414. first = false;
  3415. }
  3416. push_text(p_class->extends[i]);
  3417. }
  3418. }
  3419. push_line(" :");
  3420. increase_indent();
  3421. for (int i = 0; i < p_class->members.size(); i++) {
  3422. const ClassNode::Member &m = p_class->members[i];
  3423. switch (m.type) {
  3424. case ClassNode::Member::CLASS:
  3425. print_class(m.m_class);
  3426. break;
  3427. case ClassNode::Member::VARIABLE:
  3428. print_variable(m.variable);
  3429. break;
  3430. case ClassNode::Member::CONSTANT:
  3431. print_constant(m.constant);
  3432. break;
  3433. case ClassNode::Member::SIGNAL:
  3434. print_signal(m.signal);
  3435. break;
  3436. case ClassNode::Member::FUNCTION:
  3437. print_function(m.function);
  3438. break;
  3439. case ClassNode::Member::ENUM:
  3440. print_enum(m.m_enum);
  3441. break;
  3442. case ClassNode::Member::ENUM_VALUE:
  3443. break; // Nothing. Will be printed by enum.
  3444. case ClassNode::Member::UNDEFINED:
  3445. push_line("<unknown member>");
  3446. break;
  3447. }
  3448. }
  3449. decrease_indent();
  3450. }
  3451. void GDScriptParser::TreePrinter::print_constant(ConstantNode *p_constant) {
  3452. push_text("Constant ");
  3453. print_identifier(p_constant->identifier);
  3454. increase_indent();
  3455. push_line();
  3456. push_text("= ");
  3457. if (p_constant->initializer == nullptr) {
  3458. push_text("<missing value>");
  3459. } else {
  3460. print_expression(p_constant->initializer);
  3461. }
  3462. decrease_indent();
  3463. push_line();
  3464. }
  3465. void GDScriptParser::TreePrinter::print_dictionary(DictionaryNode *p_dictionary) {
  3466. push_line("{");
  3467. increase_indent();
  3468. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  3469. print_expression(p_dictionary->elements[i].key);
  3470. if (p_dictionary->style == DictionaryNode::PYTHON_DICT) {
  3471. push_text(" : ");
  3472. } else {
  3473. push_text(" = ");
  3474. }
  3475. print_expression(p_dictionary->elements[i].value);
  3476. push_line(" ,");
  3477. }
  3478. decrease_indent();
  3479. push_text("}");
  3480. }
  3481. void GDScriptParser::TreePrinter::print_expression(ExpressionNode *p_expression) {
  3482. if (p_expression == nullptr) {
  3483. push_text("<invalid expression>");
  3484. return;
  3485. }
  3486. switch (p_expression->type) {
  3487. case Node::ARRAY:
  3488. print_array(static_cast<ArrayNode *>(p_expression));
  3489. break;
  3490. case Node::ASSIGNMENT:
  3491. print_assignment(static_cast<AssignmentNode *>(p_expression));
  3492. break;
  3493. case Node::AWAIT:
  3494. print_await(static_cast<AwaitNode *>(p_expression));
  3495. break;
  3496. case Node::BINARY_OPERATOR:
  3497. print_binary_op(static_cast<BinaryOpNode *>(p_expression));
  3498. break;
  3499. case Node::CALL:
  3500. print_call(static_cast<CallNode *>(p_expression));
  3501. break;
  3502. case Node::CAST:
  3503. print_cast(static_cast<CastNode *>(p_expression));
  3504. break;
  3505. case Node::DICTIONARY:
  3506. print_dictionary(static_cast<DictionaryNode *>(p_expression));
  3507. break;
  3508. case Node::GET_NODE:
  3509. print_get_node(static_cast<GetNodeNode *>(p_expression));
  3510. break;
  3511. case Node::IDENTIFIER:
  3512. print_identifier(static_cast<IdentifierNode *>(p_expression));
  3513. break;
  3514. case Node::LAMBDA:
  3515. print_lambda(static_cast<LambdaNode *>(p_expression));
  3516. break;
  3517. case Node::LITERAL:
  3518. print_literal(static_cast<LiteralNode *>(p_expression));
  3519. break;
  3520. case Node::PRELOAD:
  3521. print_preload(static_cast<PreloadNode *>(p_expression));
  3522. break;
  3523. case Node::SELF:
  3524. print_self(static_cast<SelfNode *>(p_expression));
  3525. break;
  3526. case Node::SUBSCRIPT:
  3527. print_subscript(static_cast<SubscriptNode *>(p_expression));
  3528. break;
  3529. case Node::TERNARY_OPERATOR:
  3530. print_ternary_op(static_cast<TernaryOpNode *>(p_expression));
  3531. break;
  3532. case Node::UNARY_OPERATOR:
  3533. print_unary_op(static_cast<UnaryOpNode *>(p_expression));
  3534. break;
  3535. default:
  3536. push_text(vformat("<unknown expression %d>", p_expression->type));
  3537. break;
  3538. }
  3539. }
  3540. void GDScriptParser::TreePrinter::print_enum(EnumNode *p_enum) {
  3541. push_text("Enum ");
  3542. if (p_enum->identifier != nullptr) {
  3543. print_identifier(p_enum->identifier);
  3544. } else {
  3545. push_text("<unnamed>");
  3546. }
  3547. push_line(" {");
  3548. increase_indent();
  3549. for (int i = 0; i < p_enum->values.size(); i++) {
  3550. const EnumNode::Value &item = p_enum->values[i];
  3551. print_identifier(item.identifier);
  3552. push_text(" = ");
  3553. push_text(itos(item.value));
  3554. push_line(" ,");
  3555. }
  3556. decrease_indent();
  3557. push_line("}");
  3558. }
  3559. void GDScriptParser::TreePrinter::print_for(ForNode *p_for) {
  3560. push_text("For ");
  3561. print_identifier(p_for->variable);
  3562. push_text(" IN ");
  3563. print_expression(p_for->list);
  3564. push_line(" :");
  3565. increase_indent();
  3566. print_suite(p_for->loop);
  3567. decrease_indent();
  3568. }
  3569. void GDScriptParser::TreePrinter::print_function(FunctionNode *p_function, const String &p_context) {
  3570. for (const AnnotationNode *E : p_function->annotations) {
  3571. print_annotation(E);
  3572. }
  3573. push_text(p_context);
  3574. push_text(" ");
  3575. if (p_function->identifier) {
  3576. print_identifier(p_function->identifier);
  3577. } else {
  3578. push_text("<anonymous>");
  3579. }
  3580. push_text("( ");
  3581. for (int i = 0; i < p_function->parameters.size(); i++) {
  3582. if (i > 0) {
  3583. push_text(" , ");
  3584. }
  3585. print_parameter(p_function->parameters[i]);
  3586. }
  3587. push_line(" ) :");
  3588. increase_indent();
  3589. print_suite(p_function->body);
  3590. decrease_indent();
  3591. }
  3592. void GDScriptParser::TreePrinter::print_get_node(GetNodeNode *p_get_node) {
  3593. push_text("$");
  3594. if (p_get_node->string != nullptr) {
  3595. print_literal(p_get_node->string);
  3596. } else {
  3597. for (int i = 0; i < p_get_node->chain.size(); i++) {
  3598. if (i > 0) {
  3599. push_text("/");
  3600. }
  3601. print_identifier(p_get_node->chain[i]);
  3602. }
  3603. }
  3604. }
  3605. void GDScriptParser::TreePrinter::print_identifier(IdentifierNode *p_identifier) {
  3606. push_text(p_identifier->name);
  3607. }
  3608. void GDScriptParser::TreePrinter::print_if(IfNode *p_if, bool p_is_elif) {
  3609. if (p_is_elif) {
  3610. push_text("Elif ");
  3611. } else {
  3612. push_text("If ");
  3613. }
  3614. print_expression(p_if->condition);
  3615. push_line(" :");
  3616. increase_indent();
  3617. print_suite(p_if->true_block);
  3618. decrease_indent();
  3619. // FIXME: Properly detect "elif" blocks.
  3620. if (p_if->false_block != nullptr) {
  3621. push_line("Else :");
  3622. increase_indent();
  3623. print_suite(p_if->false_block);
  3624. decrease_indent();
  3625. }
  3626. }
  3627. void GDScriptParser::TreePrinter::print_lambda(LambdaNode *p_lambda) {
  3628. print_function(p_lambda->function, "Lambda");
  3629. push_text("| captures [ ");
  3630. for (int i = 0; i < p_lambda->captures.size(); i++) {
  3631. if (i > 0) {
  3632. push_text(" , ");
  3633. }
  3634. push_text(p_lambda->captures[i]->name.operator String());
  3635. }
  3636. push_line(" ]");
  3637. }
  3638. void GDScriptParser::TreePrinter::print_literal(LiteralNode *p_literal) {
  3639. // Prefix for string types.
  3640. switch (p_literal->value.get_type()) {
  3641. case Variant::NODE_PATH:
  3642. push_text("^\"");
  3643. break;
  3644. case Variant::STRING:
  3645. push_text("\"");
  3646. break;
  3647. case Variant::STRING_NAME:
  3648. push_text("&\"");
  3649. break;
  3650. default:
  3651. break;
  3652. }
  3653. push_text(p_literal->value);
  3654. // Suffix for string types.
  3655. switch (p_literal->value.get_type()) {
  3656. case Variant::NODE_PATH:
  3657. case Variant::STRING:
  3658. case Variant::STRING_NAME:
  3659. push_text("\"");
  3660. break;
  3661. default:
  3662. break;
  3663. }
  3664. }
  3665. void GDScriptParser::TreePrinter::print_match(MatchNode *p_match) {
  3666. push_text("Match ");
  3667. print_expression(p_match->test);
  3668. push_line(" :");
  3669. increase_indent();
  3670. for (int i = 0; i < p_match->branches.size(); i++) {
  3671. print_match_branch(p_match->branches[i]);
  3672. }
  3673. decrease_indent();
  3674. }
  3675. void GDScriptParser::TreePrinter::print_match_branch(MatchBranchNode *p_match_branch) {
  3676. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  3677. if (i > 0) {
  3678. push_text(" , ");
  3679. }
  3680. print_match_pattern(p_match_branch->patterns[i]);
  3681. }
  3682. push_line(" :");
  3683. increase_indent();
  3684. print_suite(p_match_branch->block);
  3685. decrease_indent();
  3686. }
  3687. void GDScriptParser::TreePrinter::print_match_pattern(PatternNode *p_match_pattern) {
  3688. switch (p_match_pattern->pattern_type) {
  3689. case PatternNode::PT_LITERAL:
  3690. print_literal(p_match_pattern->literal);
  3691. break;
  3692. case PatternNode::PT_WILDCARD:
  3693. push_text("_");
  3694. break;
  3695. case PatternNode::PT_REST:
  3696. push_text("..");
  3697. break;
  3698. case PatternNode::PT_BIND:
  3699. push_text("Var ");
  3700. print_identifier(p_match_pattern->bind);
  3701. break;
  3702. case PatternNode::PT_EXPRESSION:
  3703. print_expression(p_match_pattern->expression);
  3704. break;
  3705. case PatternNode::PT_ARRAY:
  3706. push_text("[ ");
  3707. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  3708. if (i > 0) {
  3709. push_text(" , ");
  3710. }
  3711. print_match_pattern(p_match_pattern->array[i]);
  3712. }
  3713. push_text(" ]");
  3714. break;
  3715. case PatternNode::PT_DICTIONARY:
  3716. push_text("{ ");
  3717. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  3718. if (i > 0) {
  3719. push_text(" , ");
  3720. }
  3721. if (p_match_pattern->dictionary[i].key != nullptr) {
  3722. // Key can be null for rest pattern.
  3723. print_expression(p_match_pattern->dictionary[i].key);
  3724. push_text(" : ");
  3725. }
  3726. print_match_pattern(p_match_pattern->dictionary[i].value_pattern);
  3727. }
  3728. push_text(" }");
  3729. break;
  3730. }
  3731. }
  3732. void GDScriptParser::TreePrinter::print_parameter(ParameterNode *p_parameter) {
  3733. print_identifier(p_parameter->identifier);
  3734. if (p_parameter->datatype_specifier != nullptr) {
  3735. push_text(" : ");
  3736. print_type(p_parameter->datatype_specifier);
  3737. }
  3738. if (p_parameter->default_value != nullptr) {
  3739. push_text(" = ");
  3740. print_expression(p_parameter->default_value);
  3741. }
  3742. }
  3743. void GDScriptParser::TreePrinter::print_preload(PreloadNode *p_preload) {
  3744. push_text(R"(Preload ( ")");
  3745. push_text(p_preload->resolved_path);
  3746. push_text(R"(" )");
  3747. }
  3748. void GDScriptParser::TreePrinter::print_return(ReturnNode *p_return) {
  3749. push_text("Return");
  3750. if (p_return->return_value != nullptr) {
  3751. push_text(" ");
  3752. print_expression(p_return->return_value);
  3753. }
  3754. push_line();
  3755. }
  3756. void GDScriptParser::TreePrinter::print_self(SelfNode *p_self) {
  3757. push_text("Self(");
  3758. if (p_self->current_class->identifier != nullptr) {
  3759. print_identifier(p_self->current_class->identifier);
  3760. } else {
  3761. push_text("<main class>");
  3762. }
  3763. push_text(")");
  3764. }
  3765. void GDScriptParser::TreePrinter::print_signal(SignalNode *p_signal) {
  3766. push_text("Signal ");
  3767. print_identifier(p_signal->identifier);
  3768. push_text("( ");
  3769. for (int i = 0; i < p_signal->parameters.size(); i++) {
  3770. print_parameter(p_signal->parameters[i]);
  3771. }
  3772. push_line(" )");
  3773. }
  3774. void GDScriptParser::TreePrinter::print_subscript(SubscriptNode *p_subscript) {
  3775. print_expression(p_subscript->base);
  3776. if (p_subscript->is_attribute) {
  3777. push_text(".");
  3778. print_identifier(p_subscript->attribute);
  3779. } else {
  3780. push_text("[ ");
  3781. print_expression(p_subscript->index);
  3782. push_text(" ]");
  3783. }
  3784. }
  3785. void GDScriptParser::TreePrinter::print_statement(Node *p_statement) {
  3786. switch (p_statement->type) {
  3787. case Node::ASSERT:
  3788. print_assert(static_cast<AssertNode *>(p_statement));
  3789. break;
  3790. case Node::VARIABLE:
  3791. print_variable(static_cast<VariableNode *>(p_statement));
  3792. break;
  3793. case Node::CONSTANT:
  3794. print_constant(static_cast<ConstantNode *>(p_statement));
  3795. break;
  3796. case Node::IF:
  3797. print_if(static_cast<IfNode *>(p_statement));
  3798. break;
  3799. case Node::FOR:
  3800. print_for(static_cast<ForNode *>(p_statement));
  3801. break;
  3802. case Node::WHILE:
  3803. print_while(static_cast<WhileNode *>(p_statement));
  3804. break;
  3805. case Node::MATCH:
  3806. print_match(static_cast<MatchNode *>(p_statement));
  3807. break;
  3808. case Node::RETURN:
  3809. print_return(static_cast<ReturnNode *>(p_statement));
  3810. break;
  3811. case Node::BREAK:
  3812. push_line("Break");
  3813. break;
  3814. case Node::CONTINUE:
  3815. push_line("Continue");
  3816. break;
  3817. case Node::PASS:
  3818. push_line("Pass");
  3819. break;
  3820. case Node::BREAKPOINT:
  3821. push_line("Breakpoint");
  3822. break;
  3823. case Node::ASSIGNMENT:
  3824. print_assignment(static_cast<AssignmentNode *>(p_statement));
  3825. break;
  3826. default:
  3827. if (p_statement->is_expression()) {
  3828. print_expression(static_cast<ExpressionNode *>(p_statement));
  3829. push_line();
  3830. } else {
  3831. push_line(vformat("<unknown statement %d>", p_statement->type));
  3832. }
  3833. break;
  3834. }
  3835. }
  3836. void GDScriptParser::TreePrinter::print_suite(SuiteNode *p_suite) {
  3837. for (int i = 0; i < p_suite->statements.size(); i++) {
  3838. print_statement(p_suite->statements[i]);
  3839. }
  3840. }
  3841. void GDScriptParser::TreePrinter::print_ternary_op(TernaryOpNode *p_ternary_op) {
  3842. // Surround in parenthesis for disambiguation.
  3843. push_text("(");
  3844. print_expression(p_ternary_op->true_expr);
  3845. push_text(") IF (");
  3846. print_expression(p_ternary_op->condition);
  3847. push_text(") ELSE (");
  3848. print_expression(p_ternary_op->false_expr);
  3849. push_text(")");
  3850. }
  3851. void GDScriptParser::TreePrinter::print_type(TypeNode *p_type) {
  3852. if (p_type->type_chain.is_empty()) {
  3853. push_text("Void");
  3854. } else {
  3855. for (int i = 0; i < p_type->type_chain.size(); i++) {
  3856. if (i > 0) {
  3857. push_text(".");
  3858. }
  3859. print_identifier(p_type->type_chain[i]);
  3860. }
  3861. }
  3862. }
  3863. void GDScriptParser::TreePrinter::print_unary_op(UnaryOpNode *p_unary_op) {
  3864. // Surround in parenthesis for disambiguation.
  3865. push_text("(");
  3866. switch (p_unary_op->operation) {
  3867. case UnaryOpNode::OP_POSITIVE:
  3868. push_text("+");
  3869. break;
  3870. case UnaryOpNode::OP_NEGATIVE:
  3871. push_text("-");
  3872. break;
  3873. case UnaryOpNode::OP_LOGIC_NOT:
  3874. push_text("NOT");
  3875. break;
  3876. case UnaryOpNode::OP_COMPLEMENT:
  3877. push_text("~");
  3878. break;
  3879. }
  3880. print_expression(p_unary_op->operand);
  3881. // Surround in parenthesis for disambiguation.
  3882. push_text(")");
  3883. }
  3884. void GDScriptParser::TreePrinter::print_variable(VariableNode *p_variable) {
  3885. for (const AnnotationNode *E : p_variable->annotations) {
  3886. print_annotation(E);
  3887. }
  3888. push_text("Variable ");
  3889. print_identifier(p_variable->identifier);
  3890. push_text(" : ");
  3891. if (p_variable->datatype_specifier != nullptr) {
  3892. print_type(p_variable->datatype_specifier);
  3893. } else if (p_variable->infer_datatype) {
  3894. push_text("<inferred type>");
  3895. } else {
  3896. push_text("Variant");
  3897. }
  3898. increase_indent();
  3899. push_line();
  3900. push_text("= ");
  3901. if (p_variable->initializer == nullptr) {
  3902. push_text("<default value>");
  3903. } else {
  3904. print_expression(p_variable->initializer);
  3905. }
  3906. push_line();
  3907. if (p_variable->property != VariableNode::PROP_NONE) {
  3908. if (p_variable->getter != nullptr) {
  3909. push_text("Get");
  3910. if (p_variable->property == VariableNode::PROP_INLINE) {
  3911. push_line(":");
  3912. increase_indent();
  3913. print_suite(p_variable->getter);
  3914. decrease_indent();
  3915. } else {
  3916. push_line(" =");
  3917. increase_indent();
  3918. print_identifier(p_variable->getter_pointer);
  3919. push_line();
  3920. decrease_indent();
  3921. }
  3922. }
  3923. if (p_variable->setter != nullptr) {
  3924. push_text("Set (");
  3925. if (p_variable->property == VariableNode::PROP_INLINE) {
  3926. if (p_variable->setter_parameter != nullptr) {
  3927. print_identifier(p_variable->setter_parameter);
  3928. } else {
  3929. push_text("<missing>");
  3930. }
  3931. push_line("):");
  3932. increase_indent();
  3933. print_suite(p_variable->setter);
  3934. decrease_indent();
  3935. } else {
  3936. push_line(" =");
  3937. increase_indent();
  3938. print_identifier(p_variable->setter_pointer);
  3939. push_line();
  3940. decrease_indent();
  3941. }
  3942. }
  3943. }
  3944. decrease_indent();
  3945. push_line();
  3946. }
  3947. void GDScriptParser::TreePrinter::print_while(WhileNode *p_while) {
  3948. push_text("While ");
  3949. print_expression(p_while->condition);
  3950. push_line(" :");
  3951. increase_indent();
  3952. print_suite(p_while->loop);
  3953. decrease_indent();
  3954. }
  3955. void GDScriptParser::TreePrinter::print_tree(const GDScriptParser &p_parser) {
  3956. ERR_FAIL_COND_MSG(p_parser.get_tree() == nullptr, "Parse the code before printing the parse tree.");
  3957. if (p_parser.is_tool()) {
  3958. push_line("@tool");
  3959. }
  3960. if (!p_parser.get_tree()->icon_path.is_empty()) {
  3961. push_text(R"(@icon (")");
  3962. push_text(p_parser.get_tree()->icon_path);
  3963. push_line("\")");
  3964. }
  3965. print_class(p_parser.get_tree());
  3966. print_line(printed);
  3967. }
  3968. #endif // DEBUG_ENABLED