gdscript_parser.cpp 155 KB

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