gdscript_parser.cpp 186 KB

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