gdscript_parser.cpp 177 KB

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