gdscript_parser.cpp 177 KB

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