gdscript_parser.cpp 168 KB

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