gdscript_parser.cpp 185 KB

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