gdscript_parser.cpp 168 KB

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