gdscript_parser.cpp 147 KB

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