gdscript_parser.cpp 156 KB

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