gdscript_parser.cpp 158 KB

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