gdscript_parser.cpp 167 KB

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