2
0

gdscript_parser.cpp 185 KB

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