gdscript_parser.cpp 147 KB

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