gdscript_parser.cpp 182 KB

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