gdscript_parser.cpp 179 KB

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