gdscript_parser.cpp 191 KB

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