gdscript_parser.cpp 196 KB

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