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 "core/config/project_settings.h"
  32. #include "core/io/file_access.h"
  33. #include "core/io/resource_loader.h"
  34. #include "core/math/math_defs.h"
  35. #include "gdscript.h"
  36. #include "scene/main/multiplayer_api.h"
  37. #ifdef DEBUG_ENABLED
  38. #include "core/os/os.h"
  39. #include "core/string/string_builder.h"
  40. #include "gdscript_warning.h"
  41. #include "servers/text_server.h"
  42. #endif // DEBUG_ENABLED
  43. #ifdef TOOLS_ENABLED
  44. #include "editor/editor_settings.h"
  45. #endif // TOOLS_ENABLED
  46. static HashMap<StringName, Variant::Type> builtin_types;
  47. Variant::Type GDScriptParser::get_builtin_type(const StringName &p_type) {
  48. if (builtin_types.is_empty()) {
  49. for (int i = 1; i < Variant::VARIANT_MAX; i++) {
  50. builtin_types[Variant::get_type_name((Variant::Type)i)] = (Variant::Type)i;
  51. }
  52. }
  53. if (builtin_types.has(p_type)) {
  54. return builtin_types[p_type];
  55. }
  56. return Variant::VARIANT_MAX;
  57. }
  58. void GDScriptParser::cleanup() {
  59. builtin_types.clear();
  60. }
  61. void GDScriptParser::get_annotation_list(List<MethodInfo> *r_annotations) const {
  62. for (const KeyValue<StringName, AnnotationInfo> &E : valid_annotations) {
  63. r_annotations->push_back(E.value.info);
  64. }
  65. }
  66. bool GDScriptParser::annotation_exists(const String &p_annotation_name) const {
  67. return valid_annotations.has(p_annotation_name);
  68. }
  69. GDScriptParser::GDScriptParser() {
  70. // Register valid annotations.
  71. // TODO: Should this be static?
  72. register_annotation(MethodInfo("@tool"), AnnotationInfo::SCRIPT, &GDScriptParser::tool_annotation);
  73. register_annotation(MethodInfo("@icon", PropertyInfo(Variant::STRING, "icon_path")), AnnotationInfo::SCRIPT, &GDScriptParser::icon_annotation);
  74. register_annotation(MethodInfo("@static_unload"), AnnotationInfo::SCRIPT, &GDScriptParser::static_unload_annotation);
  75. register_annotation(MethodInfo("@onready"), AnnotationInfo::VARIABLE, &GDScriptParser::onready_annotation);
  76. // Export annotations.
  77. register_annotation(MethodInfo("@export"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_NONE, Variant::NIL>);
  78. register_annotation(MethodInfo("@export_enum", PropertyInfo(Variant::STRING, "names")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_ENUM, Variant::NIL>, varray(), true);
  79. register_annotation(MethodInfo("@export_file", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FILE, Variant::STRING>, varray(""), true);
  80. register_annotation(MethodInfo("@export_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_DIR, Variant::STRING>);
  81. register_annotation(MethodInfo("@export_global_file", PropertyInfo(Variant::STRING, "filter")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_FILE, Variant::STRING>, varray(""), true);
  82. register_annotation(MethodInfo("@export_global_dir"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_GLOBAL_DIR, Variant::STRING>);
  83. register_annotation(MethodInfo("@export_multiline"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_MULTILINE_TEXT, Variant::STRING>);
  84. register_annotation(MethodInfo("@export_placeholder", PropertyInfo(Variant::STRING, "placeholder")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_PLACEHOLDER_TEXT, Variant::STRING>);
  85. 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);
  86. register_annotation(MethodInfo("@export_exp_easing", PropertyInfo(Variant::STRING, "hints")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_EXP_EASING, Variant::FLOAT>, varray(""), true);
  87. register_annotation(MethodInfo("@export_color_no_alpha"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_COLOR_NO_ALPHA, Variant::COLOR>);
  88. 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);
  89. register_annotation(MethodInfo("@export_flags", PropertyInfo(Variant::STRING, "names")), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_FLAGS, Variant::INT>, varray(), true);
  90. register_annotation(MethodInfo("@export_flags_2d_render"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_RENDER, Variant::INT>);
  91. register_annotation(MethodInfo("@export_flags_2d_physics"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_PHYSICS, Variant::INT>);
  92. register_annotation(MethodInfo("@export_flags_2d_navigation"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_2D_NAVIGATION, Variant::INT>);
  93. register_annotation(MethodInfo("@export_flags_3d_render"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_RENDER, Variant::INT>);
  94. register_annotation(MethodInfo("@export_flags_3d_physics"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_PHYSICS, Variant::INT>);
  95. register_annotation(MethodInfo("@export_flags_3d_navigation"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_3D_NAVIGATION, Variant::INT>);
  96. register_annotation(MethodInfo("@export_flags_avoidance"), AnnotationInfo::VARIABLE, &GDScriptParser::export_annotations<PROPERTY_HINT_LAYERS_AVOIDANCE, Variant::INT>);
  97. // Export grouping annotations.
  98. register_annotation(MethodInfo("@export_category", PropertyInfo(Variant::STRING, "name")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_CATEGORY>);
  99. register_annotation(MethodInfo("@export_group", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::STRING, "prefix")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_GROUP>, varray(""));
  100. register_annotation(MethodInfo("@export_subgroup", PropertyInfo(Variant::STRING, "name"), PropertyInfo(Variant::STRING, "prefix")), AnnotationInfo::STANDALONE, &GDScriptParser::export_group_annotations<PROPERTY_USAGE_SUBGROUP>, varray(""));
  101. // Warning annotations.
  102. 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);
  103. // Networking.
  104. 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), true);
  105. #ifdef DEBUG_ENABLED
  106. is_ignoring_warnings = !(bool)GLOBAL_GET("debug/gdscript/warnings/enable");
  107. #endif
  108. }
  109. GDScriptParser::~GDScriptParser() {
  110. clear();
  111. }
  112. void GDScriptParser::clear() {
  113. while (list != nullptr) {
  114. Node *element = list;
  115. list = list->next;
  116. memdelete(element);
  117. }
  118. head = nullptr;
  119. list = nullptr;
  120. _is_tool = false;
  121. for_completion = false;
  122. errors.clear();
  123. multiline_stack.clear();
  124. nodes_in_progress.clear();
  125. }
  126. void GDScriptParser::push_error(const String &p_message, const Node *p_origin) {
  127. // TODO: Improve error reporting by pointing at source code.
  128. // TODO: Errors might point at more than one place at once (e.g. show previous declaration).
  129. panic_mode = true;
  130. // TODO: Improve positional information.
  131. if (p_origin == nullptr) {
  132. errors.push_back({ p_message, current.start_line, current.start_column });
  133. } else {
  134. errors.push_back({ p_message, p_origin->start_line, p_origin->leftmost_column });
  135. }
  136. }
  137. #ifdef DEBUG_ENABLED
  138. void GDScriptParser::push_warning(const Node *p_source, GDScriptWarning::Code p_code, const Vector<String> &p_symbols) {
  139. ERR_FAIL_COND(p_source == nullptr);
  140. if (is_ignoring_warnings) {
  141. return;
  142. }
  143. if (GLOBAL_GET("debug/gdscript/warnings/exclude_addons").booleanize() && script_path.begins_with("res://addons/")) {
  144. return;
  145. }
  146. if (ignored_warnings.has(p_code)) {
  147. return;
  148. }
  149. int warn_level = (int)GLOBAL_GET(GDScriptWarning::get_settings_path_from_code(p_code));
  150. if (!warn_level) {
  151. return;
  152. }
  153. GDScriptWarning warning;
  154. warning.code = p_code;
  155. warning.symbols = p_symbols;
  156. warning.start_line = p_source->start_line;
  157. warning.end_line = p_source->end_line;
  158. warning.leftmost_column = p_source->leftmost_column;
  159. warning.rightmost_column = p_source->rightmost_column;
  160. if (warn_level == GDScriptWarning::WarnLevel::ERROR) {
  161. push_error(warning.get_message() + String(" (Warning treated as error.)"), p_source);
  162. return;
  163. }
  164. List<GDScriptWarning>::Element *before = nullptr;
  165. for (List<GDScriptWarning>::Element *E = warnings.front(); E; E = E->next()) {
  166. if (E->get().start_line > warning.start_line) {
  167. break;
  168. }
  169. before = E;
  170. }
  171. if (before) {
  172. warnings.insert_after(before, warning);
  173. } else {
  174. warnings.push_front(warning);
  175. }
  176. }
  177. #endif
  178. void GDScriptParser::make_completion_context(CompletionType p_type, Node *p_node, int p_argument, bool p_force) {
  179. if (!for_completion || (!p_force && completion_context.type != COMPLETION_NONE)) {
  180. return;
  181. }
  182. if (previous.cursor_place != GDScriptTokenizer::CURSOR_MIDDLE && previous.cursor_place != GDScriptTokenizer::CURSOR_END && current.cursor_place == GDScriptTokenizer::CURSOR_NONE) {
  183. return;
  184. }
  185. CompletionContext context;
  186. context.type = p_type;
  187. context.current_class = current_class;
  188. context.current_function = current_function;
  189. context.current_suite = current_suite;
  190. context.current_line = tokenizer.get_cursor_line();
  191. context.current_argument = p_argument;
  192. context.node = p_node;
  193. completion_context = context;
  194. }
  195. void GDScriptParser::make_completion_context(CompletionType p_type, Variant::Type p_builtin_type, bool p_force) {
  196. if (!for_completion || (!p_force && completion_context.type != COMPLETION_NONE)) {
  197. return;
  198. }
  199. if (previous.cursor_place != GDScriptTokenizer::CURSOR_MIDDLE && previous.cursor_place != GDScriptTokenizer::CURSOR_END && current.cursor_place == GDScriptTokenizer::CURSOR_NONE) {
  200. return;
  201. }
  202. CompletionContext context;
  203. context.type = p_type;
  204. context.current_class = current_class;
  205. context.current_function = current_function;
  206. context.current_suite = current_suite;
  207. context.current_line = tokenizer.get_cursor_line();
  208. context.builtin_type = p_builtin_type;
  209. completion_context = context;
  210. }
  211. void GDScriptParser::push_completion_call(Node *p_call) {
  212. if (!for_completion) {
  213. return;
  214. }
  215. CompletionCall call;
  216. call.call = p_call;
  217. call.argument = 0;
  218. completion_call_stack.push_back(call);
  219. if (previous.cursor_place == GDScriptTokenizer::CURSOR_MIDDLE || previous.cursor_place == GDScriptTokenizer::CURSOR_END || current.cursor_place == GDScriptTokenizer::CURSOR_BEGINNING) {
  220. completion_call = call;
  221. }
  222. }
  223. void GDScriptParser::pop_completion_call() {
  224. if (!for_completion) {
  225. return;
  226. }
  227. ERR_FAIL_COND_MSG(completion_call_stack.is_empty(), "Trying to pop empty completion call stack");
  228. completion_call_stack.pop_back();
  229. }
  230. void GDScriptParser::set_last_completion_call_arg(int p_argument) {
  231. if (!for_completion || passed_cursor) {
  232. return;
  233. }
  234. ERR_FAIL_COND_MSG(completion_call_stack.is_empty(), "Trying to set argument on empty completion call stack");
  235. completion_call_stack.back()->get().argument = p_argument;
  236. }
  237. Error GDScriptParser::parse(const String &p_source_code, const String &p_script_path, bool p_for_completion) {
  238. clear();
  239. String source = p_source_code;
  240. int cursor_line = -1;
  241. int cursor_column = -1;
  242. for_completion = p_for_completion;
  243. int tab_size = 4;
  244. #ifdef TOOLS_ENABLED
  245. if (EditorSettings::get_singleton()) {
  246. tab_size = EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");
  247. }
  248. #endif // TOOLS_ENABLED
  249. if (p_for_completion) {
  250. // Remove cursor sentinel char.
  251. const Vector<String> lines = p_source_code.split("\n");
  252. cursor_line = 1;
  253. cursor_column = 1;
  254. for (int i = 0; i < lines.size(); i++) {
  255. bool found = false;
  256. const String &line = lines[i];
  257. for (int j = 0; j < line.size(); j++) {
  258. if (line[j] == char32_t(0xFFFF)) {
  259. found = true;
  260. break;
  261. } else if (line[j] == '\t') {
  262. cursor_column += tab_size - 1;
  263. }
  264. cursor_column++;
  265. }
  266. if (found) {
  267. break;
  268. }
  269. cursor_line++;
  270. cursor_column = 1;
  271. }
  272. source = source.replace_first(String::chr(0xFFFF), String());
  273. }
  274. tokenizer.set_source_code(source);
  275. tokenizer.set_cursor_position(cursor_line, cursor_column);
  276. script_path = p_script_path;
  277. current = tokenizer.scan();
  278. // Avoid error or newline as the first token.
  279. // The latter can mess with the parser when opening files filled exclusively with comments and newlines.
  280. while (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::NEWLINE) {
  281. if (current.type == GDScriptTokenizer::Token::ERROR) {
  282. push_error(current.literal);
  283. }
  284. current = tokenizer.scan();
  285. }
  286. #ifdef DEBUG_ENABLED
  287. // Warn about parsing an empty script file:
  288. if (current.type == GDScriptTokenizer::Token::TK_EOF) {
  289. // Create a dummy Node for the warning, pointing to the very beginning of the file
  290. Node *nd = alloc_node<PassNode>();
  291. nd->start_line = 1;
  292. nd->start_column = 0;
  293. nd->end_line = 1;
  294. nd->leftmost_column = 0;
  295. nd->rightmost_column = 0;
  296. push_warning(nd, GDScriptWarning::EMPTY_FILE);
  297. }
  298. #endif
  299. push_multiline(false); // Keep one for the whole parsing.
  300. parse_program();
  301. pop_multiline();
  302. #ifdef DEBUG_ENABLED
  303. if (multiline_stack.size() > 0) {
  304. ERR_PRINT("Parser bug: Imbalanced multiline stack.");
  305. }
  306. #endif
  307. if (errors.is_empty()) {
  308. return OK;
  309. } else {
  310. return ERR_PARSE_ERROR;
  311. }
  312. }
  313. GDScriptTokenizer::Token GDScriptParser::advance() {
  314. lambda_ended = false; // Empty marker since we're past the end in any case.
  315. if (current.type == GDScriptTokenizer::Token::TK_EOF) {
  316. ERR_FAIL_COND_V_MSG(current.type == GDScriptTokenizer::Token::TK_EOF, current, "GDScript parser bug: Trying to advance past the end of stream.");
  317. }
  318. if (for_completion && !completion_call_stack.is_empty()) {
  319. if (completion_call.call == nullptr && tokenizer.is_past_cursor()) {
  320. completion_call = completion_call_stack.back()->get();
  321. passed_cursor = true;
  322. }
  323. }
  324. previous = current;
  325. current = tokenizer.scan();
  326. while (current.type == GDScriptTokenizer::Token::ERROR) {
  327. push_error(current.literal);
  328. current = tokenizer.scan();
  329. }
  330. for (Node *n : nodes_in_progress) {
  331. update_extents(n);
  332. }
  333. return previous;
  334. }
  335. bool GDScriptParser::match(GDScriptTokenizer::Token::Type p_token_type) {
  336. if (!check(p_token_type)) {
  337. return false;
  338. }
  339. advance();
  340. return true;
  341. }
  342. bool GDScriptParser::check(GDScriptTokenizer::Token::Type p_token_type) const {
  343. if (p_token_type == GDScriptTokenizer::Token::IDENTIFIER) {
  344. return current.is_identifier();
  345. }
  346. return current.type == p_token_type;
  347. }
  348. bool GDScriptParser::consume(GDScriptTokenizer::Token::Type p_token_type, const String &p_error_message) {
  349. if (match(p_token_type)) {
  350. return true;
  351. }
  352. push_error(p_error_message);
  353. return false;
  354. }
  355. bool GDScriptParser::is_at_end() const {
  356. return check(GDScriptTokenizer::Token::TK_EOF);
  357. }
  358. void GDScriptParser::synchronize() {
  359. panic_mode = false;
  360. while (!is_at_end()) {
  361. if (previous.type == GDScriptTokenizer::Token::NEWLINE || previous.type == GDScriptTokenizer::Token::SEMICOLON) {
  362. return;
  363. }
  364. switch (current.type) {
  365. case GDScriptTokenizer::Token::CLASS:
  366. case GDScriptTokenizer::Token::FUNC:
  367. case GDScriptTokenizer::Token::STATIC:
  368. case GDScriptTokenizer::Token::VAR:
  369. case GDScriptTokenizer::Token::CONST:
  370. case GDScriptTokenizer::Token::SIGNAL:
  371. //case GDScriptTokenizer::Token::IF: // Can also be inside expressions.
  372. case GDScriptTokenizer::Token::FOR:
  373. case GDScriptTokenizer::Token::WHILE:
  374. case GDScriptTokenizer::Token::MATCH:
  375. case GDScriptTokenizer::Token::RETURN:
  376. case GDScriptTokenizer::Token::ANNOTATION:
  377. return;
  378. default:
  379. // Do nothing.
  380. break;
  381. }
  382. advance();
  383. }
  384. }
  385. void GDScriptParser::push_multiline(bool p_state) {
  386. multiline_stack.push_back(p_state);
  387. tokenizer.set_multiline_mode(p_state);
  388. if (p_state) {
  389. // Consume potential whitespace tokens already waiting in line.
  390. while (current.type == GDScriptTokenizer::Token::NEWLINE || current.type == GDScriptTokenizer::Token::INDENT || current.type == GDScriptTokenizer::Token::DEDENT) {
  391. current = tokenizer.scan(); // Don't call advance() here, as we don't want to change the previous token.
  392. }
  393. }
  394. }
  395. void GDScriptParser::pop_multiline() {
  396. ERR_FAIL_COND_MSG(multiline_stack.size() == 0, "Parser bug: trying to pop from multiline stack without available value.");
  397. multiline_stack.pop_back();
  398. tokenizer.set_multiline_mode(multiline_stack.size() > 0 ? multiline_stack.back()->get() : false);
  399. }
  400. bool GDScriptParser::is_statement_end_token() const {
  401. return check(GDScriptTokenizer::Token::NEWLINE) || check(GDScriptTokenizer::Token::SEMICOLON) || check(GDScriptTokenizer::Token::TK_EOF);
  402. }
  403. bool GDScriptParser::is_statement_end() const {
  404. return lambda_ended || in_lambda || is_statement_end_token();
  405. }
  406. void GDScriptParser::end_statement(const String &p_context) {
  407. bool found = false;
  408. while (is_statement_end() && !is_at_end()) {
  409. // Remove sequential newlines/semicolons.
  410. if (is_statement_end_token()) {
  411. // Only consume if this is an actual token.
  412. advance();
  413. } else if (lambda_ended) {
  414. lambda_ended = false; // Consume this "token".
  415. found = true;
  416. break;
  417. } else {
  418. if (!found) {
  419. lambda_ended = true; // Mark the lambda as done since we found something else to end the statement.
  420. found = true;
  421. }
  422. break;
  423. }
  424. found = true;
  425. }
  426. if (!found && !is_at_end()) {
  427. push_error(vformat(R"(Expected end of statement after %s, found "%s" instead.)", p_context, current.get_name()));
  428. }
  429. }
  430. void GDScriptParser::parse_program() {
  431. head = alloc_node<ClassNode>();
  432. head->fqcn = script_path;
  433. current_class = head;
  434. bool can_have_class_or_extends = true;
  435. while (!check(GDScriptTokenizer::Token::TK_EOF)) {
  436. if (match(GDScriptTokenizer::Token::ANNOTATION)) {
  437. AnnotationNode *annotation = parse_annotation(AnnotationInfo::SCRIPT | AnnotationInfo::STANDALONE | AnnotationInfo::CLASS_LEVEL);
  438. if (annotation != nullptr) {
  439. if (annotation->applies_to(AnnotationInfo::SCRIPT)) {
  440. // `@icon` needs to be applied in the parser. See GH-72444.
  441. if (annotation->name == SNAME("@icon")) {
  442. annotation->apply(this, head);
  443. } else {
  444. head->annotations.push_back(annotation);
  445. }
  446. } else {
  447. annotation_stack.push_back(annotation);
  448. // This annotation must appear after script-level annotations
  449. // and class_name/extends (ex: could be @onready or @export),
  450. // so we stop looking for script-level stuff.
  451. can_have_class_or_extends = false;
  452. break;
  453. }
  454. }
  455. } else if (check(GDScriptTokenizer::Token::LITERAL) && current.literal.get_type() == Variant::STRING) {
  456. // Allow strings in class body as multiline comments.
  457. advance();
  458. if (!match(GDScriptTokenizer::Token::NEWLINE)) {
  459. push_error("Expected newline after comment string.");
  460. }
  461. } else {
  462. break;
  463. }
  464. }
  465. while (can_have_class_or_extends) {
  466. // Order here doesn't matter, but there should be only one of each at most.
  467. switch (current.type) {
  468. case GDScriptTokenizer::Token::CLASS_NAME:
  469. advance();
  470. if (head->identifier != nullptr) {
  471. push_error(R"("class_name" can only be used once.)");
  472. } else {
  473. parse_class_name();
  474. }
  475. break;
  476. case GDScriptTokenizer::Token::EXTENDS:
  477. advance();
  478. if (head->extends_used) {
  479. push_error(R"("extends" can only be used once.)");
  480. } else {
  481. parse_extends();
  482. end_statement("superclass");
  483. }
  484. break;
  485. case GDScriptTokenizer::Token::LITERAL:
  486. if (current.literal.get_type() == Variant::STRING) {
  487. // Allow strings in class body as multiline comments.
  488. advance();
  489. if (!match(GDScriptTokenizer::Token::NEWLINE)) {
  490. push_error("Expected newline after comment string.");
  491. }
  492. break;
  493. }
  494. [[fallthrough]];
  495. default:
  496. // No tokens are allowed between script annotations and class/extends.
  497. can_have_class_or_extends = false;
  498. break;
  499. }
  500. if (panic_mode) {
  501. synchronize();
  502. }
  503. }
  504. parse_class_body(true);
  505. complete_extents(head);
  506. #ifdef TOOLS_ENABLED
  507. for (const KeyValue<int, GDScriptTokenizer::CommentData> &E : tokenizer.get_comments()) {
  508. if (E.value.new_line && E.value.comment.begins_with("##")) {
  509. class_doc_line = MIN(class_doc_line, E.key);
  510. }
  511. }
  512. if (has_comment(class_doc_line)) {
  513. get_class_doc_comment(class_doc_line, head->doc_brief_description, head->doc_description, head->doc_tutorials, false);
  514. }
  515. #endif // TOOLS_ENABLED
  516. if (!check(GDScriptTokenizer::Token::TK_EOF)) {
  517. push_error("Expected end of file.");
  518. }
  519. clear_unused_annotations();
  520. }
  521. GDScriptParser::ClassNode *GDScriptParser::find_class(const String &p_qualified_name) const {
  522. String first = p_qualified_name.get_slice("::", 0);
  523. Vector<String> class_names;
  524. GDScriptParser::ClassNode *result = nullptr;
  525. // Empty initial name means start at the head.
  526. if (first.is_empty() || (head->identifier && first == head->identifier->name)) {
  527. class_names = p_qualified_name.split("::");
  528. result = head;
  529. } else if (p_qualified_name.begins_with(script_path)) {
  530. // Script path could have a class path separator("::") in it.
  531. class_names = p_qualified_name.trim_prefix(script_path).split("::");
  532. result = head;
  533. } else if (head->has_member(first)) {
  534. class_names = p_qualified_name.split("::");
  535. GDScriptParser::ClassNode::Member member = head->get_member(first);
  536. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  537. result = member.m_class;
  538. }
  539. }
  540. // Starts at index 1 because index 0 was handled above.
  541. for (int i = 1; result != nullptr && i < class_names.size(); i++) {
  542. String current_name = class_names[i];
  543. GDScriptParser::ClassNode *next = nullptr;
  544. if (result->has_member(current_name)) {
  545. GDScriptParser::ClassNode::Member member = result->get_member(current_name);
  546. if (member.type == GDScriptParser::ClassNode::Member::CLASS) {
  547. next = member.m_class;
  548. }
  549. }
  550. result = next;
  551. }
  552. return result;
  553. }
  554. bool GDScriptParser::has_class(const GDScriptParser::ClassNode *p_class) const {
  555. if (head->fqcn.is_empty() && p_class->fqcn.get_slice("::", 0).is_empty()) {
  556. return p_class == head;
  557. } else if (p_class->fqcn.begins_with(head->fqcn)) {
  558. return find_class(p_class->fqcn.trim_prefix(head->fqcn)) == p_class;
  559. }
  560. return false;
  561. }
  562. GDScriptParser::ClassNode *GDScriptParser::parse_class(bool p_is_static) {
  563. ClassNode *n_class = alloc_node<ClassNode>();
  564. ClassNode *previous_class = current_class;
  565. current_class = n_class;
  566. n_class->outer = previous_class;
  567. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the class name after "class".)")) {
  568. n_class->identifier = parse_identifier();
  569. if (n_class->outer) {
  570. String fqcn = n_class->outer->fqcn;
  571. if (fqcn.is_empty()) {
  572. fqcn = script_path;
  573. }
  574. n_class->fqcn = fqcn + "::" + n_class->identifier->name;
  575. } else {
  576. n_class->fqcn = n_class->identifier->name;
  577. }
  578. }
  579. if (match(GDScriptTokenizer::Token::EXTENDS)) {
  580. parse_extends();
  581. }
  582. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after class declaration.)");
  583. bool multiline = match(GDScriptTokenizer::Token::NEWLINE);
  584. if (multiline && !consume(GDScriptTokenizer::Token::INDENT, R"(Expected indented block after class declaration.)")) {
  585. current_class = previous_class;
  586. complete_extents(n_class);
  587. return n_class;
  588. }
  589. if (match(GDScriptTokenizer::Token::EXTENDS)) {
  590. if (n_class->extends_used) {
  591. push_error(R"(Cannot use "extends" more than once in the same class.)");
  592. }
  593. parse_extends();
  594. end_statement("superclass");
  595. }
  596. parse_class_body(multiline);
  597. complete_extents(n_class);
  598. if (multiline) {
  599. consume(GDScriptTokenizer::Token::DEDENT, R"(Missing unindent at the end of the class body.)");
  600. }
  601. current_class = previous_class;
  602. return n_class;
  603. }
  604. void GDScriptParser::parse_class_name() {
  605. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for the global class name after "class_name".)")) {
  606. current_class->identifier = parse_identifier();
  607. current_class->fqcn = String(current_class->identifier->name);
  608. }
  609. if (match(GDScriptTokenizer::Token::EXTENDS)) {
  610. // Allow extends on the same line.
  611. parse_extends();
  612. end_statement("superclass");
  613. } else {
  614. end_statement("class_name statement");
  615. }
  616. }
  617. void GDScriptParser::parse_extends() {
  618. current_class->extends_used = true;
  619. int chain_index = 0;
  620. if (match(GDScriptTokenizer::Token::LITERAL)) {
  621. if (previous.literal.get_type() != Variant::STRING) {
  622. push_error(vformat(R"(Only strings or identifiers can be used after "extends", found "%s" instead.)", Variant::get_type_name(previous.literal.get_type())));
  623. }
  624. current_class->extends_path = previous.literal;
  625. if (!match(GDScriptTokenizer::Token::PERIOD)) {
  626. return;
  627. }
  628. }
  629. make_completion_context(COMPLETION_INHERIT_TYPE, current_class, chain_index++);
  630. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after "extends".)")) {
  631. return;
  632. }
  633. current_class->extends.push_back(parse_identifier());
  634. while (match(GDScriptTokenizer::Token::PERIOD)) {
  635. make_completion_context(COMPLETION_INHERIT_TYPE, current_class, chain_index++);
  636. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected superclass name after ".".)")) {
  637. return;
  638. }
  639. current_class->extends.push_back(parse_identifier());
  640. }
  641. }
  642. template <class T>
  643. void GDScriptParser::parse_class_member(T *(GDScriptParser::*p_parse_function)(bool), AnnotationInfo::TargetKind p_target, const String &p_member_kind, bool p_is_static) {
  644. advance();
  645. #ifdef TOOLS_ENABLED
  646. int doc_comment_line = previous.start_line - 1;
  647. #endif // TOOLS_ENABLED
  648. // Consume annotations.
  649. List<AnnotationNode *> annotations;
  650. while (!annotation_stack.is_empty()) {
  651. AnnotationNode *last_annotation = annotation_stack.back()->get();
  652. if (last_annotation->applies_to(p_target)) {
  653. annotations.push_front(last_annotation);
  654. annotation_stack.pop_back();
  655. } else {
  656. push_error(vformat(R"(Annotation "%s" cannot be applied to a %s.)", last_annotation->name, p_member_kind));
  657. clear_unused_annotations();
  658. }
  659. #ifdef TOOLS_ENABLED
  660. if (last_annotation->start_line == doc_comment_line) {
  661. doc_comment_line--;
  662. }
  663. #endif // TOOLS_ENABLED
  664. }
  665. T *member = (this->*p_parse_function)(p_is_static);
  666. if (member == nullptr) {
  667. return;
  668. }
  669. for (AnnotationNode *&annotation : annotations) {
  670. member->annotations.push_back(annotation);
  671. }
  672. #ifdef TOOLS_ENABLED
  673. // Consume doc comments.
  674. class_doc_line = MIN(class_doc_line, doc_comment_line - 1);
  675. // Check whether current line has a doc comment
  676. if (has_comment(previous.start_line, true)) {
  677. member->doc_description = get_doc_comment(previous.start_line, true);
  678. } else if (has_comment(doc_comment_line, true)) {
  679. if constexpr (std::is_same_v<T, ClassNode>) {
  680. get_class_doc_comment(doc_comment_line, member->doc_brief_description, member->doc_description, member->doc_tutorials, true);
  681. } else {
  682. member->doc_description = get_doc_comment(doc_comment_line);
  683. }
  684. }
  685. #endif // TOOLS_ENABLED
  686. if (member->identifier != nullptr) {
  687. if (!((String)member->identifier->name).is_empty()) { // Enums may be unnamed.
  688. #ifdef DEBUG_ENABLED
  689. List<MethodInfo> gdscript_funcs;
  690. GDScriptLanguage::get_singleton()->get_public_functions(&gdscript_funcs);
  691. for (MethodInfo &info : gdscript_funcs) {
  692. if (info.name == member->identifier->name) {
  693. push_warning(member->identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_member_kind, member->identifier->name, "built-in function");
  694. }
  695. }
  696. if (Variant::has_utility_function(member->identifier->name)) {
  697. push_warning(member->identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, p_member_kind, member->identifier->name, "built-in function");
  698. }
  699. #endif
  700. if (current_class->members_indices.has(member->identifier->name)) {
  701. 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);
  702. } else {
  703. current_class->add_member(member);
  704. }
  705. } else {
  706. current_class->add_member(member);
  707. }
  708. }
  709. }
  710. void GDScriptParser::parse_class_body(bool p_is_multiline) {
  711. bool class_end = false;
  712. bool next_is_static = false;
  713. while (!class_end && !is_at_end()) {
  714. GDScriptTokenizer::Token token = current;
  715. switch (token.type) {
  716. case GDScriptTokenizer::Token::VAR:
  717. parse_class_member(&GDScriptParser::parse_variable, AnnotationInfo::VARIABLE, "variable", next_is_static);
  718. if (next_is_static) {
  719. current_class->has_static_data = true;
  720. }
  721. break;
  722. case GDScriptTokenizer::Token::CONST:
  723. parse_class_member(&GDScriptParser::parse_constant, AnnotationInfo::CONSTANT, "constant");
  724. break;
  725. case GDScriptTokenizer::Token::SIGNAL:
  726. parse_class_member(&GDScriptParser::parse_signal, AnnotationInfo::SIGNAL, "signal");
  727. break;
  728. case GDScriptTokenizer::Token::FUNC:
  729. parse_class_member(&GDScriptParser::parse_function, AnnotationInfo::FUNCTION, "function", next_is_static);
  730. break;
  731. case GDScriptTokenizer::Token::CLASS:
  732. parse_class_member(&GDScriptParser::parse_class, AnnotationInfo::CLASS, "class");
  733. break;
  734. case GDScriptTokenizer::Token::ENUM:
  735. parse_class_member(&GDScriptParser::parse_enum, AnnotationInfo::NONE, "enum");
  736. break;
  737. case GDScriptTokenizer::Token::STATIC: {
  738. advance();
  739. next_is_static = true;
  740. if (!check(GDScriptTokenizer::Token::FUNC) && !check(GDScriptTokenizer::Token::VAR)) {
  741. push_error(R"(Expected "func" or "var" after "static".)");
  742. }
  743. } break;
  744. case GDScriptTokenizer::Token::ANNOTATION: {
  745. advance();
  746. // Check for standalone and class-level annotations.
  747. AnnotationNode *annotation = parse_annotation(AnnotationInfo::STANDALONE | AnnotationInfo::CLASS_LEVEL);
  748. if (annotation != nullptr) {
  749. if (annotation->applies_to(AnnotationInfo::STANDALONE)) {
  750. if (previous.type != GDScriptTokenizer::Token::NEWLINE) {
  751. push_error(R"(Expected newline after a standalone annotation.)");
  752. }
  753. if (annotation->name == SNAME("@export_category") || annotation->name == SNAME("@export_group") || annotation->name == SNAME("@export_subgroup")) {
  754. current_class->add_member_group(annotation);
  755. } else {
  756. // For potential non-group standalone annotations.
  757. push_error(R"(Unexpected standalone annotation in class body.)");
  758. }
  759. } else {
  760. annotation_stack.push_back(annotation);
  761. }
  762. }
  763. break;
  764. }
  765. case GDScriptTokenizer::Token::PASS:
  766. advance();
  767. end_statement(R"("pass")");
  768. break;
  769. case GDScriptTokenizer::Token::DEDENT:
  770. class_end = true;
  771. break;
  772. case GDScriptTokenizer::Token::LITERAL:
  773. if (current.literal.get_type() == Variant::STRING) {
  774. // Allow strings in class body as multiline comments.
  775. advance();
  776. if (!match(GDScriptTokenizer::Token::NEWLINE)) {
  777. push_error("Expected newline after comment string.");
  778. }
  779. break;
  780. }
  781. [[fallthrough]];
  782. default:
  783. // Display a completion with identifiers.
  784. make_completion_context(COMPLETION_IDENTIFIER, nullptr);
  785. push_error(vformat(R"(Unexpected "%s" in class body.)", current.get_name()));
  786. advance();
  787. break;
  788. }
  789. if (token.type != GDScriptTokenizer::Token::STATIC) {
  790. next_is_static = false;
  791. }
  792. if (panic_mode) {
  793. synchronize();
  794. }
  795. if (!p_is_multiline) {
  796. class_end = true;
  797. }
  798. }
  799. }
  800. GDScriptParser::VariableNode *GDScriptParser::parse_variable(bool p_is_static) {
  801. return parse_variable(p_is_static, true);
  802. }
  803. GDScriptParser::VariableNode *GDScriptParser::parse_variable(bool p_is_static, bool p_allow_property) {
  804. VariableNode *variable = alloc_node<VariableNode>();
  805. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected variable name after "var".)")) {
  806. complete_extents(variable);
  807. return nullptr;
  808. }
  809. variable->identifier = parse_identifier();
  810. variable->export_info.name = variable->identifier->name;
  811. variable->is_static = p_is_static;
  812. if (match(GDScriptTokenizer::Token::COLON)) {
  813. if (check(GDScriptTokenizer::Token::NEWLINE)) {
  814. if (p_allow_property) {
  815. advance();
  816. return parse_property(variable, true);
  817. } else {
  818. push_error(R"(Expected type after ":")");
  819. complete_extents(variable);
  820. return nullptr;
  821. }
  822. } else if (check((GDScriptTokenizer::Token::EQUAL))) {
  823. // Infer type.
  824. variable->infer_datatype = true;
  825. } else {
  826. if (p_allow_property) {
  827. make_completion_context(COMPLETION_PROPERTY_DECLARATION_OR_TYPE, variable);
  828. if (check(GDScriptTokenizer::Token::IDENTIFIER)) {
  829. // Check if get or set.
  830. if (current.get_identifier() == "get" || current.get_identifier() == "set") {
  831. return parse_property(variable, false);
  832. }
  833. }
  834. }
  835. // Parse type.
  836. variable->datatype_specifier = parse_type();
  837. }
  838. }
  839. if (match(GDScriptTokenizer::Token::EQUAL)) {
  840. // Initializer.
  841. variable->initializer = parse_expression(false);
  842. if (variable->initializer == nullptr) {
  843. push_error(R"(Expected expression for variable initial value after "=".)");
  844. }
  845. variable->assignments++;
  846. }
  847. if (p_allow_property && match(GDScriptTokenizer::Token::COLON)) {
  848. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  849. return parse_property(variable, true);
  850. } else {
  851. return parse_property(variable, false);
  852. }
  853. }
  854. complete_extents(variable);
  855. end_statement("variable declaration");
  856. return variable;
  857. }
  858. GDScriptParser::VariableNode *GDScriptParser::parse_property(VariableNode *p_variable, bool p_need_indent) {
  859. if (p_need_indent) {
  860. if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected indented block for property after ":".)")) {
  861. complete_extents(p_variable);
  862. return nullptr;
  863. }
  864. }
  865. VariableNode *property = p_variable;
  866. make_completion_context(COMPLETION_PROPERTY_DECLARATION, property);
  867. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected "get" or "set" for property declaration.)")) {
  868. complete_extents(p_variable);
  869. return nullptr;
  870. }
  871. IdentifierNode *function = parse_identifier();
  872. if (check(GDScriptTokenizer::Token::EQUAL)) {
  873. p_variable->property = VariableNode::PROP_SETGET;
  874. } else {
  875. p_variable->property = VariableNode::PROP_INLINE;
  876. if (!p_need_indent) {
  877. push_error("Property with inline code must go to an indented block.");
  878. }
  879. }
  880. bool getter_used = false;
  881. bool setter_used = false;
  882. // Run with a loop because order doesn't matter.
  883. for (int i = 0; i < 2; i++) {
  884. if (function->name == SNAME("set")) {
  885. if (setter_used) {
  886. push_error(R"(Properties can only have one setter.)");
  887. } else {
  888. parse_property_setter(property);
  889. setter_used = true;
  890. }
  891. } else if (function->name == SNAME("get")) {
  892. if (getter_used) {
  893. push_error(R"(Properties can only have one getter.)");
  894. } else {
  895. parse_property_getter(property);
  896. getter_used = true;
  897. }
  898. } else {
  899. // TODO: Update message to only have the missing one if it's the case.
  900. push_error(R"(Expected "get" or "set" for property declaration.)");
  901. }
  902. if (i == 0 && p_variable->property == VariableNode::PROP_SETGET) {
  903. if (match(GDScriptTokenizer::Token::COMMA)) {
  904. // Consume potential newline.
  905. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  906. if (!p_need_indent) {
  907. push_error(R"(Inline setter/getter setting cannot span across multiple lines (use "\\"" if needed).)");
  908. }
  909. }
  910. } else {
  911. break;
  912. }
  913. }
  914. if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
  915. break;
  916. }
  917. function = parse_identifier();
  918. }
  919. complete_extents(p_variable);
  920. if (p_variable->property == VariableNode::PROP_SETGET) {
  921. end_statement("property declaration");
  922. }
  923. if (p_need_indent) {
  924. consume(GDScriptTokenizer::Token::DEDENT, R"(Expected end of indented block for property.)");
  925. }
  926. return property;
  927. }
  928. void GDScriptParser::parse_property_setter(VariableNode *p_variable) {
  929. switch (p_variable->property) {
  930. case VariableNode::PROP_INLINE: {
  931. FunctionNode *function = alloc_node<FunctionNode>();
  932. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  933. complete_extents(identifier);
  934. identifier->name = "@" + p_variable->identifier->name + "_setter";
  935. function->identifier = identifier;
  936. function->is_static = p_variable->is_static;
  937. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "set".)");
  938. ParameterNode *parameter = alloc_node<ParameterNode>();
  939. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected parameter name after "(".)")) {
  940. reset_extents(parameter, previous);
  941. p_variable->setter_parameter = parse_identifier();
  942. parameter->identifier = p_variable->setter_parameter;
  943. function->parameters_indices[parameter->identifier->name] = 0;
  944. function->parameters.push_back(parameter);
  945. }
  946. complete_extents(parameter);
  947. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after parameter name.)*");
  948. consume(GDScriptTokenizer::Token::COLON, R"*(Expected ":" after ")".)*");
  949. FunctionNode *previous_function = current_function;
  950. current_function = function;
  951. if (p_variable->setter_parameter != nullptr) {
  952. SuiteNode *body = alloc_node<SuiteNode>();
  953. body->add_local(parameter, function);
  954. function->body = parse_suite("setter declaration", body);
  955. p_variable->setter = function;
  956. }
  957. current_function = previous_function;
  958. complete_extents(function);
  959. break;
  960. }
  961. case VariableNode::PROP_SETGET:
  962. consume(GDScriptTokenizer::Token::EQUAL, R"(Expected "=" after "set")");
  963. make_completion_context(COMPLETION_PROPERTY_METHOD, p_variable);
  964. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected setter function name after "=".)")) {
  965. p_variable->setter_pointer = parse_identifier();
  966. }
  967. break;
  968. case VariableNode::PROP_NONE:
  969. break; // Unreachable.
  970. }
  971. }
  972. void GDScriptParser::parse_property_getter(VariableNode *p_variable) {
  973. switch (p_variable->property) {
  974. case VariableNode::PROP_INLINE: {
  975. FunctionNode *function = alloc_node<FunctionNode>();
  976. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "get".)");
  977. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  978. complete_extents(identifier);
  979. identifier->name = "@" + p_variable->identifier->name + "_getter";
  980. function->identifier = identifier;
  981. function->is_static = p_variable->is_static;
  982. FunctionNode *previous_function = current_function;
  983. current_function = function;
  984. SuiteNode *body = alloc_node<SuiteNode>();
  985. function->body = parse_suite("getter declaration", body);
  986. p_variable->getter = function;
  987. current_function = previous_function;
  988. complete_extents(function);
  989. break;
  990. }
  991. case VariableNode::PROP_SETGET:
  992. consume(GDScriptTokenizer::Token::EQUAL, R"(Expected "=" after "get")");
  993. make_completion_context(COMPLETION_PROPERTY_METHOD, p_variable);
  994. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected getter function name after "=".)")) {
  995. p_variable->getter_pointer = parse_identifier();
  996. }
  997. break;
  998. case VariableNode::PROP_NONE:
  999. break; // Unreachable.
  1000. }
  1001. }
  1002. GDScriptParser::ConstantNode *GDScriptParser::parse_constant(bool p_is_static) {
  1003. ConstantNode *constant = alloc_node<ConstantNode>();
  1004. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected constant name after "const".)")) {
  1005. return nullptr;
  1006. }
  1007. constant->identifier = parse_identifier();
  1008. if (match(GDScriptTokenizer::Token::COLON)) {
  1009. if (check((GDScriptTokenizer::Token::EQUAL))) {
  1010. // Infer type.
  1011. constant->infer_datatype = true;
  1012. } else {
  1013. // Parse type.
  1014. constant->datatype_specifier = parse_type();
  1015. }
  1016. }
  1017. if (consume(GDScriptTokenizer::Token::EQUAL, R"(Expected initializer after constant name.)")) {
  1018. // Initializer.
  1019. constant->initializer = parse_expression(false);
  1020. if (constant->initializer == nullptr) {
  1021. push_error(R"(Expected initializer expression for constant.)");
  1022. complete_extents(constant);
  1023. return nullptr;
  1024. }
  1025. } else {
  1026. complete_extents(constant);
  1027. return nullptr;
  1028. }
  1029. complete_extents(constant);
  1030. end_statement("constant declaration");
  1031. return constant;
  1032. }
  1033. GDScriptParser::ParameterNode *GDScriptParser::parse_parameter() {
  1034. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected parameter name.)")) {
  1035. return nullptr;
  1036. }
  1037. ParameterNode *parameter = alloc_node<ParameterNode>();
  1038. parameter->identifier = parse_identifier();
  1039. if (match(GDScriptTokenizer::Token::COLON)) {
  1040. if (check((GDScriptTokenizer::Token::EQUAL))) {
  1041. // Infer type.
  1042. parameter->infer_datatype = true;
  1043. } else {
  1044. // Parse type.
  1045. make_completion_context(COMPLETION_TYPE_NAME, parameter);
  1046. parameter->datatype_specifier = parse_type();
  1047. }
  1048. }
  1049. if (match(GDScriptTokenizer::Token::EQUAL)) {
  1050. // Default value.
  1051. parameter->initializer = parse_expression(false);
  1052. }
  1053. complete_extents(parameter);
  1054. return parameter;
  1055. }
  1056. GDScriptParser::SignalNode *GDScriptParser::parse_signal(bool p_is_static) {
  1057. SignalNode *signal = alloc_node<SignalNode>();
  1058. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected signal name after "signal".)")) {
  1059. complete_extents(signal);
  1060. return nullptr;
  1061. }
  1062. signal->identifier = parse_identifier();
  1063. if (check(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  1064. push_multiline(true);
  1065. advance();
  1066. do {
  1067. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1068. // Allow for trailing comma.
  1069. break;
  1070. }
  1071. ParameterNode *parameter = parse_parameter();
  1072. if (parameter == nullptr) {
  1073. push_error("Expected signal parameter name.");
  1074. break;
  1075. }
  1076. if (parameter->initializer != nullptr) {
  1077. push_error(R"(Signal parameters cannot have a default value.)");
  1078. }
  1079. if (signal->parameters_indices.has(parameter->identifier->name)) {
  1080. push_error(vformat(R"(Parameter with name "%s" was already declared for this signal.)", parameter->identifier->name));
  1081. } else {
  1082. signal->parameters_indices[parameter->identifier->name] = signal->parameters.size();
  1083. signal->parameters.push_back(parameter);
  1084. }
  1085. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  1086. pop_multiline();
  1087. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after signal parameters.)*");
  1088. }
  1089. complete_extents(signal);
  1090. end_statement("signal declaration");
  1091. return signal;
  1092. }
  1093. GDScriptParser::EnumNode *GDScriptParser::parse_enum(bool p_is_static) {
  1094. EnumNode *enum_node = alloc_node<EnumNode>();
  1095. bool named = false;
  1096. if (check(GDScriptTokenizer::Token::IDENTIFIER)) {
  1097. advance();
  1098. enum_node->identifier = parse_identifier();
  1099. named = true;
  1100. }
  1101. push_multiline(true);
  1102. consume(GDScriptTokenizer::Token::BRACE_OPEN, vformat(R"(Expected "{" after %s.)", named ? "enum name" : R"("enum")"));
  1103. HashMap<StringName, int> elements;
  1104. #ifdef DEBUG_ENABLED
  1105. List<MethodInfo> gdscript_funcs;
  1106. GDScriptLanguage::get_singleton()->get_public_functions(&gdscript_funcs);
  1107. #endif
  1108. do {
  1109. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  1110. break; // Allow trailing comma.
  1111. }
  1112. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier for enum key.)")) {
  1113. EnumNode::Value item;
  1114. GDScriptParser::IdentifierNode *identifier = parse_identifier();
  1115. #ifdef DEBUG_ENABLED
  1116. if (!named) { // Named enum identifiers do not shadow anything since you can only access them with NamedEnum.ENUM_VALUE
  1117. for (MethodInfo &info : gdscript_funcs) {
  1118. if (info.name == identifier->name) {
  1119. push_warning(identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, "enum member", identifier->name, "built-in function");
  1120. }
  1121. }
  1122. if (Variant::has_utility_function(identifier->name)) {
  1123. push_warning(identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, "enum member", identifier->name, "built-in function");
  1124. } else if (ClassDB::class_exists(identifier->name)) {
  1125. push_warning(identifier, GDScriptWarning::SHADOWED_GLOBAL_IDENTIFIER, "enum member", identifier->name, "global class");
  1126. }
  1127. }
  1128. #endif
  1129. item.identifier = identifier;
  1130. item.parent_enum = enum_node;
  1131. item.line = previous.start_line;
  1132. item.leftmost_column = previous.leftmost_column;
  1133. item.rightmost_column = previous.rightmost_column;
  1134. if (elements.has(item.identifier->name)) {
  1135. push_error(vformat(R"(Name "%s" was already in this enum (at line %d).)", item.identifier->name, elements[item.identifier->name]), item.identifier);
  1136. } else if (!named) {
  1137. if (current_class->members_indices.has(item.identifier->name)) {
  1138. 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()));
  1139. }
  1140. }
  1141. elements[item.identifier->name] = item.line;
  1142. if (match(GDScriptTokenizer::Token::EQUAL)) {
  1143. ExpressionNode *value = parse_expression(false);
  1144. if (value == nullptr) {
  1145. push_error(R"(Expected expression value after "=".)");
  1146. }
  1147. item.custom_value = value;
  1148. }
  1149. item.index = enum_node->values.size();
  1150. enum_node->values.push_back(item);
  1151. if (!named) {
  1152. // Add as member of current class.
  1153. current_class->add_member(item);
  1154. }
  1155. }
  1156. } while (match(GDScriptTokenizer::Token::COMMA));
  1157. pop_multiline();
  1158. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" for enum.)");
  1159. #ifdef TOOLS_ENABLED
  1160. // Enum values documentation.
  1161. for (int i = 0; i < enum_node->values.size(); i++) {
  1162. if (i == enum_node->values.size() - 1) {
  1163. // If close bracket is same line as last value.
  1164. if (enum_node->values[i].line != previous.start_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. } else {
  1172. // If two values are same line.
  1173. if (enum_node->values[i].line != enum_node->values[i + 1].line && has_comment(enum_node->values[i].line)) {
  1174. if (named) {
  1175. enum_node->values.write[i].doc_description = get_doc_comment(enum_node->values[i].line, true);
  1176. } else {
  1177. current_class->set_enum_value_doc(enum_node->values[i].identifier->name, get_doc_comment(enum_node->values[i].line, true));
  1178. }
  1179. }
  1180. }
  1181. }
  1182. #endif // TOOLS_ENABLED
  1183. complete_extents(enum_node);
  1184. end_statement("enum");
  1185. return enum_node;
  1186. }
  1187. void GDScriptParser::parse_function_signature(FunctionNode *p_function, SuiteNode *p_body, const String &p_type) {
  1188. if (!check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE) && !is_at_end()) {
  1189. bool default_used = false;
  1190. do {
  1191. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1192. // Allow for trailing comma.
  1193. break;
  1194. }
  1195. ParameterNode *parameter = parse_parameter();
  1196. if (parameter == nullptr) {
  1197. break;
  1198. }
  1199. if (parameter->initializer != nullptr) {
  1200. default_used = true;
  1201. } else {
  1202. if (default_used) {
  1203. push_error("Cannot have mandatory parameters after optional parameters.");
  1204. continue;
  1205. }
  1206. }
  1207. if (p_function->parameters_indices.has(parameter->identifier->name)) {
  1208. push_error(vformat(R"(Parameter with name "%s" was already declared for this %s.)", parameter->identifier->name, p_type));
  1209. } else {
  1210. p_function->parameters_indices[parameter->identifier->name] = p_function->parameters.size();
  1211. p_function->parameters.push_back(parameter);
  1212. p_body->add_local(parameter, current_function);
  1213. }
  1214. } while (match(GDScriptTokenizer::Token::COMMA));
  1215. }
  1216. pop_multiline();
  1217. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, vformat(R"*(Expected closing ")" after %s parameters.)*", p_type));
  1218. if (match(GDScriptTokenizer::Token::FORWARD_ARROW)) {
  1219. make_completion_context(COMPLETION_TYPE_NAME_OR_VOID, p_function);
  1220. p_function->return_type = parse_type(true);
  1221. if (p_function->return_type == nullptr) {
  1222. push_error(R"(Expected return type or "void" after "->".)");
  1223. }
  1224. }
  1225. if (!p_function->source_lambda && p_function->identifier && p_function->identifier->name == GDScriptLanguage::get_singleton()->strings._static_init) {
  1226. if (!p_function->is_static) {
  1227. push_error(R"(Static constructor must be declared static.)");
  1228. }
  1229. if (p_function->parameters.size() != 0) {
  1230. push_error(R"(Static constructor cannot have parameters.)");
  1231. }
  1232. current_class->has_static_data = true;
  1233. }
  1234. // TODO: Improve token consumption so it synchronizes to a statement boundary. This way we can get into the function body with unrecognized tokens.
  1235. consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after %s declaration.)", p_type));
  1236. }
  1237. GDScriptParser::FunctionNode *GDScriptParser::parse_function(bool p_is_static) {
  1238. FunctionNode *function = alloc_node<FunctionNode>();
  1239. make_completion_context(COMPLETION_OVERRIDE_METHOD, function);
  1240. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after "func".)")) {
  1241. complete_extents(function);
  1242. return nullptr;
  1243. }
  1244. FunctionNode *previous_function = current_function;
  1245. current_function = function;
  1246. function->identifier = parse_identifier();
  1247. function->is_static = p_is_static;
  1248. SuiteNode *body = alloc_node<SuiteNode>();
  1249. SuiteNode *previous_suite = current_suite;
  1250. current_suite = body;
  1251. push_multiline(true);
  1252. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after function name.)");
  1253. parse_function_signature(function, body, "function");
  1254. current_suite = previous_suite;
  1255. function->body = parse_suite("function declaration", body);
  1256. current_function = previous_function;
  1257. complete_extents(function);
  1258. return function;
  1259. }
  1260. GDScriptParser::AnnotationNode *GDScriptParser::parse_annotation(uint32_t p_valid_targets) {
  1261. AnnotationNode *annotation = alloc_node<AnnotationNode>();
  1262. annotation->name = previous.literal;
  1263. make_completion_context(COMPLETION_ANNOTATION, annotation);
  1264. bool valid = true;
  1265. if (!valid_annotations.has(annotation->name)) {
  1266. push_error(vformat(R"(Unrecognized annotation: "%s".)", annotation->name));
  1267. valid = false;
  1268. }
  1269. annotation->info = &valid_annotations[annotation->name];
  1270. if (!annotation->applies_to(p_valid_targets)) {
  1271. if (annotation->applies_to(AnnotationInfo::SCRIPT)) {
  1272. push_error(vformat(R"(Annotation "%s" must be at the top of the script, before "extends" and "class_name".)", annotation->name));
  1273. } else {
  1274. push_error(vformat(R"(Annotation "%s" is not allowed in this level.)", annotation->name));
  1275. }
  1276. valid = false;
  1277. }
  1278. if (check(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  1279. push_multiline(true);
  1280. advance();
  1281. // Arguments.
  1282. push_completion_call(annotation);
  1283. make_completion_context(COMPLETION_ANNOTATION_ARGUMENTS, annotation, 0, true);
  1284. int argument_index = 0;
  1285. do {
  1286. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1287. // Allow for trailing comma.
  1288. break;
  1289. }
  1290. make_completion_context(COMPLETION_ANNOTATION_ARGUMENTS, annotation, argument_index, true);
  1291. set_last_completion_call_arg(argument_index++);
  1292. ExpressionNode *argument = parse_expression(false);
  1293. if (argument == nullptr) {
  1294. push_error("Expected expression as the annotation argument.");
  1295. valid = false;
  1296. continue;
  1297. }
  1298. annotation->arguments.push_back(argument);
  1299. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  1300. pop_multiline();
  1301. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after annotation arguments.)*");
  1302. pop_completion_call();
  1303. }
  1304. complete_extents(annotation);
  1305. match(GDScriptTokenizer::Token::NEWLINE); // Newline after annotation is optional.
  1306. if (valid) {
  1307. valid = validate_annotation_arguments(annotation);
  1308. }
  1309. return valid ? annotation : nullptr;
  1310. }
  1311. void GDScriptParser::clear_unused_annotations() {
  1312. for (const AnnotationNode *annotation : annotation_stack) {
  1313. push_error(vformat(R"(Annotation "%s" does not precede a valid target, so it will have no effect.)", annotation->name), annotation);
  1314. }
  1315. annotation_stack.clear();
  1316. }
  1317. 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) {
  1318. ERR_FAIL_COND_V_MSG(valid_annotations.has(p_info.name), false, vformat(R"(Annotation "%s" already registered.)", p_info.name));
  1319. AnnotationInfo new_annotation;
  1320. new_annotation.info = p_info;
  1321. new_annotation.info.default_arguments = p_default_arguments;
  1322. if (p_is_vararg) {
  1323. new_annotation.info.flags |= METHOD_FLAG_VARARG;
  1324. }
  1325. new_annotation.apply = p_apply;
  1326. new_annotation.target_kind = p_target_kinds;
  1327. valid_annotations[p_info.name] = new_annotation;
  1328. return true;
  1329. }
  1330. GDScriptParser::SuiteNode *GDScriptParser::parse_suite(const String &p_context, SuiteNode *p_suite, bool p_for_lambda) {
  1331. SuiteNode *suite = p_suite != nullptr ? p_suite : alloc_node<SuiteNode>();
  1332. suite->parent_block = current_suite;
  1333. suite->parent_function = current_function;
  1334. current_suite = suite;
  1335. bool multiline = false;
  1336. if (match(GDScriptTokenizer::Token::NEWLINE)) {
  1337. multiline = true;
  1338. }
  1339. if (multiline) {
  1340. if (!consume(GDScriptTokenizer::Token::INDENT, vformat(R"(Expected indented block after %s.)", p_context))) {
  1341. current_suite = suite->parent_block;
  1342. complete_extents(suite);
  1343. return suite;
  1344. }
  1345. }
  1346. reset_extents(suite, current);
  1347. int error_count = 0;
  1348. do {
  1349. if (is_at_end() || (!multiline && previous.type == GDScriptTokenizer::Token::SEMICOLON && check(GDScriptTokenizer::Token::NEWLINE))) {
  1350. break;
  1351. }
  1352. Node *statement = parse_statement();
  1353. if (statement == nullptr) {
  1354. if (error_count++ > 100) {
  1355. push_error("Too many statement errors.", suite);
  1356. break;
  1357. }
  1358. continue;
  1359. }
  1360. suite->statements.push_back(statement);
  1361. // Register locals.
  1362. switch (statement->type) {
  1363. case Node::VARIABLE: {
  1364. VariableNode *variable = static_cast<VariableNode *>(statement);
  1365. const SuiteNode::Local &local = current_suite->get_local(variable->identifier->name);
  1366. if (local.type != SuiteNode::Local::UNDEFINED) {
  1367. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", local.get_name(), variable->identifier->name), variable->identifier);
  1368. }
  1369. current_suite->add_local(variable, current_function);
  1370. break;
  1371. }
  1372. case Node::CONSTANT: {
  1373. ConstantNode *constant = static_cast<ConstantNode *>(statement);
  1374. const SuiteNode::Local &local = current_suite->get_local(constant->identifier->name);
  1375. if (local.type != SuiteNode::Local::UNDEFINED) {
  1376. String name;
  1377. if (local.type == SuiteNode::Local::CONSTANT) {
  1378. name = "constant";
  1379. } else {
  1380. name = "variable";
  1381. }
  1382. push_error(vformat(R"(There is already a %s named "%s" declared in this scope.)", name, constant->identifier->name), constant->identifier);
  1383. }
  1384. current_suite->add_local(constant, current_function);
  1385. break;
  1386. }
  1387. default:
  1388. break;
  1389. }
  1390. } while ((multiline || previous.type == GDScriptTokenizer::Token::SEMICOLON) && !check(GDScriptTokenizer::Token::DEDENT) && !lambda_ended && !is_at_end());
  1391. complete_extents(suite);
  1392. if (multiline) {
  1393. if (!lambda_ended) {
  1394. consume(GDScriptTokenizer::Token::DEDENT, vformat(R"(Missing unindent at the end of %s.)", p_context));
  1395. } else {
  1396. match(GDScriptTokenizer::Token::DEDENT);
  1397. }
  1398. } else if (previous.type == GDScriptTokenizer::Token::SEMICOLON) {
  1399. consume(GDScriptTokenizer::Token::NEWLINE, vformat(R"(Expected newline after ";" at the end of %s.)", p_context));
  1400. }
  1401. if (p_for_lambda) {
  1402. lambda_ended = true;
  1403. }
  1404. current_suite = suite->parent_block;
  1405. return suite;
  1406. }
  1407. GDScriptParser::Node *GDScriptParser::parse_statement() {
  1408. Node *result = nullptr;
  1409. #ifdef DEBUG_ENABLED
  1410. bool unreachable = current_suite->has_return && !current_suite->has_unreachable_code;
  1411. #endif
  1412. bool is_annotation = false;
  1413. switch (current.type) {
  1414. case GDScriptTokenizer::Token::PASS:
  1415. advance();
  1416. result = alloc_node<PassNode>();
  1417. complete_extents(result);
  1418. end_statement(R"("pass")");
  1419. break;
  1420. case GDScriptTokenizer::Token::VAR:
  1421. advance();
  1422. result = parse_variable(false, false);
  1423. break;
  1424. case GDScriptTokenizer::Token::CONST:
  1425. advance();
  1426. result = parse_constant(false);
  1427. break;
  1428. case GDScriptTokenizer::Token::IF:
  1429. advance();
  1430. result = parse_if();
  1431. break;
  1432. case GDScriptTokenizer::Token::FOR:
  1433. advance();
  1434. result = parse_for();
  1435. break;
  1436. case GDScriptTokenizer::Token::WHILE:
  1437. advance();
  1438. result = parse_while();
  1439. break;
  1440. case GDScriptTokenizer::Token::MATCH:
  1441. advance();
  1442. result = parse_match();
  1443. break;
  1444. case GDScriptTokenizer::Token::BREAK:
  1445. advance();
  1446. result = parse_break();
  1447. break;
  1448. case GDScriptTokenizer::Token::CONTINUE:
  1449. advance();
  1450. result = parse_continue();
  1451. break;
  1452. case GDScriptTokenizer::Token::RETURN: {
  1453. advance();
  1454. ReturnNode *n_return = alloc_node<ReturnNode>();
  1455. if (!is_statement_end()) {
  1456. if (current_function && (current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._init || current_function->identifier->name == GDScriptLanguage::get_singleton()->strings._static_init)) {
  1457. push_error(R"(Constructor cannot return a value.)");
  1458. }
  1459. n_return->return_value = parse_expression(false);
  1460. } else if (in_lambda && !is_statement_end_token()) {
  1461. // Try to parse it anyway as this might not be the statement end in a lambda.
  1462. // If this fails the expression will be nullptr, but that's the same as no return, so it's fine.
  1463. n_return->return_value = parse_expression(false);
  1464. }
  1465. complete_extents(n_return);
  1466. result = n_return;
  1467. current_suite->has_return = true;
  1468. end_statement("return statement");
  1469. break;
  1470. }
  1471. case GDScriptTokenizer::Token::BREAKPOINT:
  1472. advance();
  1473. result = alloc_node<BreakpointNode>();
  1474. complete_extents(result);
  1475. end_statement(R"("breakpoint")");
  1476. break;
  1477. case GDScriptTokenizer::Token::ASSERT:
  1478. advance();
  1479. result = parse_assert();
  1480. break;
  1481. case GDScriptTokenizer::Token::ANNOTATION: {
  1482. advance();
  1483. is_annotation = true;
  1484. AnnotationNode *annotation = parse_annotation(AnnotationInfo::STATEMENT);
  1485. if (annotation != nullptr) {
  1486. annotation_stack.push_back(annotation);
  1487. }
  1488. break;
  1489. }
  1490. default: {
  1491. // Expression statement.
  1492. ExpressionNode *expression = parse_expression(true); // Allow assignment here.
  1493. bool has_ended_lambda = false;
  1494. if (expression == nullptr) {
  1495. if (in_lambda) {
  1496. // If it's not a valid expression beginning, it might be the continuation of the outer expression where this lambda is.
  1497. lambda_ended = true;
  1498. has_ended_lambda = true;
  1499. } else {
  1500. advance();
  1501. push_error(vformat(R"(Expected statement, found "%s" instead.)", previous.get_name()));
  1502. }
  1503. } else {
  1504. end_statement("expression");
  1505. }
  1506. lambda_ended = lambda_ended || has_ended_lambda;
  1507. result = expression;
  1508. #ifdef DEBUG_ENABLED
  1509. if (expression != nullptr) {
  1510. switch (expression->type) {
  1511. case Node::CALL:
  1512. case Node::ASSIGNMENT:
  1513. case Node::AWAIT:
  1514. case Node::TERNARY_OPERATOR:
  1515. // Fine.
  1516. break;
  1517. case Node::LAMBDA:
  1518. // Standalone lambdas can't be used, so make this an error.
  1519. push_error("Standalone lambdas cannot be accessed. Consider assigning it to a variable.", expression);
  1520. break;
  1521. case Node::LITERAL:
  1522. if (static_cast<GDScriptParser::LiteralNode *>(expression)->value.get_type() == Variant::STRING) {
  1523. // Allow strings as multiline comments.
  1524. break;
  1525. }
  1526. [[fallthrough]];
  1527. default:
  1528. push_warning(expression, GDScriptWarning::STANDALONE_EXPRESSION);
  1529. }
  1530. }
  1531. #endif
  1532. break;
  1533. }
  1534. }
  1535. while (!is_annotation && result != nullptr && !annotation_stack.is_empty()) {
  1536. AnnotationNode *last_annotation = annotation_stack.back()->get();
  1537. if (last_annotation->applies_to(AnnotationInfo::STATEMENT)) {
  1538. result->annotations.push_front(last_annotation);
  1539. annotation_stack.pop_back();
  1540. } else {
  1541. push_error(vformat(R"(Annotation "%s" cannot be applied to a statement.)", last_annotation->name));
  1542. clear_unused_annotations();
  1543. }
  1544. }
  1545. #ifdef DEBUG_ENABLED
  1546. if (unreachable && result != nullptr) {
  1547. current_suite->has_unreachable_code = true;
  1548. if (current_function) {
  1549. push_warning(result, GDScriptWarning::UNREACHABLE_CODE, current_function->identifier ? current_function->identifier->name : "<anonymous lambda>");
  1550. } else {
  1551. // TODO: Properties setters and getters with unreachable code are not being warned
  1552. }
  1553. }
  1554. #endif
  1555. if (panic_mode) {
  1556. synchronize();
  1557. }
  1558. return result;
  1559. }
  1560. GDScriptParser::AssertNode *GDScriptParser::parse_assert() {
  1561. // TODO: Add assert message.
  1562. AssertNode *assert = alloc_node<AssertNode>();
  1563. push_multiline(true);
  1564. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "assert".)");
  1565. assert->condition = parse_expression(false);
  1566. if (assert->condition == nullptr) {
  1567. push_error("Expected expression to assert.");
  1568. pop_multiline();
  1569. complete_extents(assert);
  1570. return nullptr;
  1571. }
  1572. if (match(GDScriptTokenizer::Token::COMMA) && !check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  1573. assert->message = parse_expression(false);
  1574. if (assert->message == nullptr) {
  1575. push_error(R"(Expected error message for assert after ",".)");
  1576. pop_multiline();
  1577. complete_extents(assert);
  1578. return nullptr;
  1579. }
  1580. match(GDScriptTokenizer::Token::COMMA);
  1581. }
  1582. pop_multiline();
  1583. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after assert expression.)*");
  1584. complete_extents(assert);
  1585. end_statement(R"("assert")");
  1586. return assert;
  1587. }
  1588. GDScriptParser::BreakNode *GDScriptParser::parse_break() {
  1589. if (!can_break) {
  1590. push_error(R"(Cannot use "break" outside of a loop.)");
  1591. }
  1592. BreakNode *break_node = alloc_node<BreakNode>();
  1593. complete_extents(break_node);
  1594. end_statement(R"("break")");
  1595. return break_node;
  1596. }
  1597. GDScriptParser::ContinueNode *GDScriptParser::parse_continue() {
  1598. if (!can_continue) {
  1599. push_error(R"(Cannot use "continue" outside of a loop.)");
  1600. }
  1601. current_suite->has_continue = true;
  1602. ContinueNode *cont = alloc_node<ContinueNode>();
  1603. complete_extents(cont);
  1604. end_statement(R"("continue")");
  1605. return cont;
  1606. }
  1607. GDScriptParser::ForNode *GDScriptParser::parse_for() {
  1608. ForNode *n_for = alloc_node<ForNode>();
  1609. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected loop variable name after "for".)")) {
  1610. n_for->variable = parse_identifier();
  1611. }
  1612. consume(GDScriptTokenizer::Token::IN, R"(Expected "in" after "for" variable name.)");
  1613. n_for->list = parse_expression(false);
  1614. if (!n_for->list) {
  1615. push_error(R"(Expected iterable after "in".)");
  1616. }
  1617. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "for" condition.)");
  1618. // Save break/continue state.
  1619. bool could_break = can_break;
  1620. bool could_continue = can_continue;
  1621. // Allow break/continue.
  1622. can_break = true;
  1623. can_continue = true;
  1624. SuiteNode *suite = alloc_node<SuiteNode>();
  1625. if (n_for->variable) {
  1626. const SuiteNode::Local &local = current_suite->get_local(n_for->variable->name);
  1627. if (local.type != SuiteNode::Local::UNDEFINED) {
  1628. 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);
  1629. }
  1630. suite->add_local(SuiteNode::Local(n_for->variable, current_function));
  1631. }
  1632. n_for->loop = parse_suite(R"("for" block)", suite);
  1633. n_for->loop->is_loop = true;
  1634. complete_extents(n_for);
  1635. // Reset break/continue state.
  1636. can_break = could_break;
  1637. can_continue = could_continue;
  1638. return n_for;
  1639. }
  1640. GDScriptParser::IfNode *GDScriptParser::parse_if(const String &p_token) {
  1641. IfNode *n_if = alloc_node<IfNode>();
  1642. n_if->condition = parse_expression(false);
  1643. if (n_if->condition == nullptr) {
  1644. push_error(vformat(R"(Expected conditional expression after "%s".)", p_token));
  1645. }
  1646. consume(GDScriptTokenizer::Token::COLON, vformat(R"(Expected ":" after "%s" condition.)", p_token));
  1647. n_if->true_block = parse_suite(vformat(R"("%s" block)", p_token));
  1648. n_if->true_block->parent_if = n_if;
  1649. if (n_if->true_block->has_continue) {
  1650. current_suite->has_continue = true;
  1651. }
  1652. if (match(GDScriptTokenizer::Token::ELIF)) {
  1653. SuiteNode *else_block = alloc_node<SuiteNode>();
  1654. else_block->parent_function = current_function;
  1655. else_block->parent_block = current_suite;
  1656. SuiteNode *previous_suite = current_suite;
  1657. current_suite = else_block;
  1658. IfNode *elif = parse_if("elif");
  1659. else_block->statements.push_back(elif);
  1660. complete_extents(else_block);
  1661. n_if->false_block = else_block;
  1662. current_suite = previous_suite;
  1663. } else if (match(GDScriptTokenizer::Token::ELSE)) {
  1664. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "else".)");
  1665. n_if->false_block = parse_suite(R"("else" block)");
  1666. }
  1667. complete_extents(n_if);
  1668. if (n_if->false_block != nullptr && n_if->false_block->has_return && n_if->true_block->has_return) {
  1669. current_suite->has_return = true;
  1670. }
  1671. if (n_if->false_block != nullptr && n_if->false_block->has_continue) {
  1672. current_suite->has_continue = true;
  1673. }
  1674. return n_if;
  1675. }
  1676. GDScriptParser::MatchNode *GDScriptParser::parse_match() {
  1677. MatchNode *match = alloc_node<MatchNode>();
  1678. match->test = parse_expression(false);
  1679. if (match->test == nullptr) {
  1680. push_error(R"(Expected expression to test after "match".)");
  1681. }
  1682. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" expression.)");
  1683. consume(GDScriptTokenizer::Token::NEWLINE, R"(Expected a newline after "match" statement.)");
  1684. if (!consume(GDScriptTokenizer::Token::INDENT, R"(Expected an indented block after "match" statement.)")) {
  1685. complete_extents(match);
  1686. return match;
  1687. }
  1688. bool all_have_return = true;
  1689. bool have_wildcard = false;
  1690. while (!check(GDScriptTokenizer::Token::DEDENT) && !is_at_end()) {
  1691. MatchBranchNode *branch = parse_match_branch();
  1692. if (branch == nullptr) {
  1693. advance();
  1694. continue;
  1695. }
  1696. #ifdef DEBUG_ENABLED
  1697. if (have_wildcard && !branch->patterns.is_empty()) {
  1698. push_warning(branch->patterns[0], GDScriptWarning::UNREACHABLE_PATTERN);
  1699. }
  1700. #endif
  1701. have_wildcard = have_wildcard || branch->has_wildcard;
  1702. all_have_return = all_have_return && branch->block->has_return;
  1703. match->branches.push_back(branch);
  1704. }
  1705. complete_extents(match);
  1706. consume(GDScriptTokenizer::Token::DEDENT, R"(Expected an indented block after "match" statement.)");
  1707. if (all_have_return && have_wildcard) {
  1708. current_suite->has_return = true;
  1709. }
  1710. return match;
  1711. }
  1712. GDScriptParser::MatchBranchNode *GDScriptParser::parse_match_branch() {
  1713. MatchBranchNode *branch = alloc_node<MatchBranchNode>();
  1714. reset_extents(branch, current);
  1715. bool has_bind = false;
  1716. do {
  1717. PatternNode *pattern = parse_match_pattern();
  1718. if (pattern == nullptr) {
  1719. continue;
  1720. }
  1721. if (pattern->binds.size() > 0) {
  1722. has_bind = true;
  1723. }
  1724. if (branch->patterns.size() > 0 && has_bind) {
  1725. push_error(R"(Cannot use a variable bind with multiple patterns.)");
  1726. }
  1727. if (pattern->pattern_type == PatternNode::PT_REST) {
  1728. push_error(R"(Rest pattern can only be used inside array and dictionary patterns.)");
  1729. } else if (pattern->pattern_type == PatternNode::PT_BIND || pattern->pattern_type == PatternNode::PT_WILDCARD) {
  1730. branch->has_wildcard = true;
  1731. }
  1732. branch->patterns.push_back(pattern);
  1733. } while (match(GDScriptTokenizer::Token::COMMA));
  1734. if (branch->patterns.is_empty()) {
  1735. push_error(R"(No pattern found for "match" branch.)");
  1736. }
  1737. if (!consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "match" patterns.)")) {
  1738. complete_extents(branch);
  1739. return nullptr;
  1740. }
  1741. SuiteNode *suite = alloc_node<SuiteNode>();
  1742. if (branch->patterns.size() > 0) {
  1743. for (const KeyValue<StringName, IdentifierNode *> &E : branch->patterns[0]->binds) {
  1744. SuiteNode::Local local(E.value, current_function);
  1745. local.type = SuiteNode::Local::PATTERN_BIND;
  1746. suite->add_local(local);
  1747. }
  1748. }
  1749. branch->block = parse_suite("match pattern block", suite);
  1750. complete_extents(branch);
  1751. return branch;
  1752. }
  1753. GDScriptParser::PatternNode *GDScriptParser::parse_match_pattern(PatternNode *p_root_pattern) {
  1754. PatternNode *pattern = alloc_node<PatternNode>();
  1755. reset_extents(pattern, current);
  1756. switch (current.type) {
  1757. case GDScriptTokenizer::Token::VAR: {
  1758. // Bind.
  1759. advance();
  1760. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected bind name after "var".)")) {
  1761. complete_extents(pattern);
  1762. return nullptr;
  1763. }
  1764. pattern->pattern_type = PatternNode::PT_BIND;
  1765. pattern->bind = parse_identifier();
  1766. PatternNode *root_pattern = p_root_pattern == nullptr ? pattern : p_root_pattern;
  1767. if (p_root_pattern != nullptr) {
  1768. if (p_root_pattern->has_bind(pattern->bind->name)) {
  1769. push_error(vformat(R"(Bind variable name "%s" was already used in this pattern.)", pattern->bind->name));
  1770. complete_extents(pattern);
  1771. return nullptr;
  1772. }
  1773. }
  1774. if (current_suite->has_local(pattern->bind->name)) {
  1775. 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));
  1776. complete_extents(pattern);
  1777. return nullptr;
  1778. }
  1779. root_pattern->binds[pattern->bind->name] = pattern->bind;
  1780. } break;
  1781. case GDScriptTokenizer::Token::UNDERSCORE:
  1782. // Wildcard.
  1783. advance();
  1784. pattern->pattern_type = PatternNode::PT_WILDCARD;
  1785. break;
  1786. case GDScriptTokenizer::Token::PERIOD_PERIOD:
  1787. // Rest.
  1788. advance();
  1789. pattern->pattern_type = PatternNode::PT_REST;
  1790. break;
  1791. case GDScriptTokenizer::Token::BRACKET_OPEN: {
  1792. // Array.
  1793. advance();
  1794. pattern->pattern_type = PatternNode::PT_ARRAY;
  1795. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  1796. do {
  1797. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  1798. if (sub_pattern == nullptr) {
  1799. continue;
  1800. }
  1801. if (pattern->rest_used) {
  1802. push_error(R"(The ".." pattern must be the last element in the pattern array.)");
  1803. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  1804. pattern->rest_used = true;
  1805. }
  1806. pattern->array.push_back(sub_pattern);
  1807. } while (match(GDScriptTokenizer::Token::COMMA));
  1808. }
  1809. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" to close the array pattern.)");
  1810. break;
  1811. }
  1812. case GDScriptTokenizer::Token::BRACE_OPEN: {
  1813. // Dictionary.
  1814. advance();
  1815. pattern->pattern_type = PatternNode::PT_DICTIONARY;
  1816. do {
  1817. if (check(GDScriptTokenizer::Token::BRACE_CLOSE) || is_at_end()) {
  1818. break;
  1819. }
  1820. if (match(GDScriptTokenizer::Token::PERIOD_PERIOD)) {
  1821. // Rest.
  1822. if (pattern->rest_used) {
  1823. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  1824. } else {
  1825. PatternNode *sub_pattern = alloc_node<PatternNode>();
  1826. complete_extents(sub_pattern);
  1827. sub_pattern->pattern_type = PatternNode::PT_REST;
  1828. pattern->dictionary.push_back({ nullptr, sub_pattern });
  1829. pattern->rest_used = true;
  1830. }
  1831. } else {
  1832. ExpressionNode *key = parse_expression(false);
  1833. if (key == nullptr) {
  1834. push_error(R"(Expected expression as key for dictionary pattern.)");
  1835. }
  1836. if (match(GDScriptTokenizer::Token::COLON)) {
  1837. // Value pattern.
  1838. PatternNode *sub_pattern = parse_match_pattern(p_root_pattern != nullptr ? p_root_pattern : pattern);
  1839. if (sub_pattern == nullptr) {
  1840. continue;
  1841. }
  1842. if (pattern->rest_used) {
  1843. push_error(R"(The ".." pattern must be the last element in the pattern dictionary.)");
  1844. } else if (sub_pattern->pattern_type == PatternNode::PT_REST) {
  1845. push_error(R"(The ".." pattern cannot be used as a value.)");
  1846. } else {
  1847. pattern->dictionary.push_back({ key, sub_pattern });
  1848. }
  1849. } else {
  1850. // Key match only.
  1851. pattern->dictionary.push_back({ key, nullptr });
  1852. }
  1853. }
  1854. } while (match(GDScriptTokenizer::Token::COMMA));
  1855. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected "}" to close the dictionary pattern.)");
  1856. break;
  1857. }
  1858. default: {
  1859. // Expression.
  1860. ExpressionNode *expression = parse_expression(false);
  1861. if (expression == nullptr) {
  1862. push_error(R"(Expected expression for match pattern.)");
  1863. return nullptr;
  1864. } else {
  1865. if (expression->type == GDScriptParser::Node::LITERAL) {
  1866. pattern->pattern_type = PatternNode::PT_LITERAL;
  1867. } else {
  1868. pattern->pattern_type = PatternNode::PT_EXPRESSION;
  1869. }
  1870. pattern->expression = expression;
  1871. }
  1872. break;
  1873. }
  1874. }
  1875. complete_extents(pattern);
  1876. return pattern;
  1877. }
  1878. bool GDScriptParser::PatternNode::has_bind(const StringName &p_name) {
  1879. return binds.has(p_name);
  1880. }
  1881. GDScriptParser::IdentifierNode *GDScriptParser::PatternNode::get_bind(const StringName &p_name) {
  1882. return binds[p_name];
  1883. }
  1884. GDScriptParser::WhileNode *GDScriptParser::parse_while() {
  1885. WhileNode *n_while = alloc_node<WhileNode>();
  1886. n_while->condition = parse_expression(false);
  1887. if (n_while->condition == nullptr) {
  1888. push_error(R"(Expected conditional expression after "while".)");
  1889. }
  1890. consume(GDScriptTokenizer::Token::COLON, R"(Expected ":" after "while" condition.)");
  1891. // Save break/continue state.
  1892. bool could_break = can_break;
  1893. bool could_continue = can_continue;
  1894. // Allow break/continue.
  1895. can_break = true;
  1896. can_continue = true;
  1897. n_while->loop = parse_suite(R"("while" block)");
  1898. n_while->loop->is_loop = true;
  1899. complete_extents(n_while);
  1900. // Reset break/continue state.
  1901. can_break = could_break;
  1902. can_continue = could_continue;
  1903. return n_while;
  1904. }
  1905. GDScriptParser::ExpressionNode *GDScriptParser::parse_precedence(Precedence p_precedence, bool p_can_assign, bool p_stop_on_assign) {
  1906. // Switch multiline mode on for grouping tokens.
  1907. // Do this early to avoid the tokenizer generating whitespace tokens.
  1908. switch (current.type) {
  1909. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  1910. case GDScriptTokenizer::Token::BRACE_OPEN:
  1911. case GDScriptTokenizer::Token::BRACKET_OPEN:
  1912. push_multiline(true);
  1913. break;
  1914. default:
  1915. break; // Nothing to do.
  1916. }
  1917. // Completion can appear whenever an expression is expected.
  1918. make_completion_context(COMPLETION_IDENTIFIER, nullptr);
  1919. GDScriptTokenizer::Token token = current;
  1920. GDScriptTokenizer::Token::Type token_type = token.type;
  1921. if (token.is_identifier()) {
  1922. // Allow keywords that can be treated as identifiers.
  1923. token_type = GDScriptTokenizer::Token::IDENTIFIER;
  1924. }
  1925. ParseFunction prefix_rule = get_rule(token_type)->prefix;
  1926. if (prefix_rule == nullptr) {
  1927. // Expected expression. Let the caller give the proper error message.
  1928. return nullptr;
  1929. }
  1930. advance(); // Only consume the token if there's a valid rule.
  1931. ExpressionNode *previous_operand = (this->*prefix_rule)(nullptr, p_can_assign);
  1932. while (p_precedence <= get_rule(current.type)->precedence) {
  1933. if (previous_operand == nullptr || (p_stop_on_assign && current.type == GDScriptTokenizer::Token::EQUAL) || (previous_operand->type == Node::LAMBDA && lambda_ended)) {
  1934. return previous_operand;
  1935. }
  1936. // Also switch multiline mode on here for infix operators.
  1937. switch (current.type) {
  1938. // case GDScriptTokenizer::Token::BRACE_OPEN: // Not an infix operator.
  1939. case GDScriptTokenizer::Token::PARENTHESIS_OPEN:
  1940. case GDScriptTokenizer::Token::BRACKET_OPEN:
  1941. push_multiline(true);
  1942. break;
  1943. default:
  1944. break; // Nothing to do.
  1945. }
  1946. token = advance();
  1947. ParseFunction infix_rule = get_rule(token.type)->infix;
  1948. previous_operand = (this->*infix_rule)(previous_operand, p_can_assign);
  1949. }
  1950. return previous_operand;
  1951. }
  1952. GDScriptParser::ExpressionNode *GDScriptParser::parse_expression(bool p_can_assign, bool p_stop_on_assign) {
  1953. return parse_precedence(PREC_ASSIGNMENT, p_can_assign, p_stop_on_assign);
  1954. }
  1955. GDScriptParser::IdentifierNode *GDScriptParser::parse_identifier() {
  1956. IdentifierNode *identifier = static_cast<IdentifierNode *>(parse_identifier(nullptr, false));
  1957. #ifdef DEBUG_ENABLED
  1958. // Check for spoofing here (if available in TextServer) since this isn't called inside expressions. This is only relevant for declarations.
  1959. if (identifier && TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier->name.operator String())) {
  1960. push_warning(identifier, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier->name.operator String());
  1961. }
  1962. #endif
  1963. return identifier;
  1964. }
  1965. GDScriptParser::ExpressionNode *GDScriptParser::parse_identifier(ExpressionNode *p_previous_operand, bool p_can_assign) {
  1966. if (!previous.is_identifier()) {
  1967. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing identifier node without identifier token.");
  1968. }
  1969. IdentifierNode *identifier = alloc_node<IdentifierNode>();
  1970. complete_extents(identifier);
  1971. identifier->name = previous.get_identifier();
  1972. if (current_suite != nullptr && current_suite->has_local(identifier->name)) {
  1973. const SuiteNode::Local &declaration = current_suite->get_local(identifier->name);
  1974. identifier->source_function = declaration.source_function;
  1975. switch (declaration.type) {
  1976. case SuiteNode::Local::CONSTANT:
  1977. identifier->source = IdentifierNode::LOCAL_CONSTANT;
  1978. identifier->constant_source = declaration.constant;
  1979. declaration.constant->usages++;
  1980. break;
  1981. case SuiteNode::Local::VARIABLE:
  1982. identifier->source = IdentifierNode::LOCAL_VARIABLE;
  1983. identifier->variable_source = declaration.variable;
  1984. declaration.variable->usages++;
  1985. break;
  1986. case SuiteNode::Local::PARAMETER:
  1987. identifier->source = IdentifierNode::FUNCTION_PARAMETER;
  1988. identifier->parameter_source = declaration.parameter;
  1989. declaration.parameter->usages++;
  1990. break;
  1991. case SuiteNode::Local::FOR_VARIABLE:
  1992. identifier->source = IdentifierNode::LOCAL_ITERATOR;
  1993. identifier->bind_source = declaration.bind;
  1994. declaration.bind->usages++;
  1995. break;
  1996. case SuiteNode::Local::PATTERN_BIND:
  1997. identifier->source = IdentifierNode::LOCAL_BIND;
  1998. identifier->bind_source = declaration.bind;
  1999. declaration.bind->usages++;
  2000. break;
  2001. case SuiteNode::Local::UNDEFINED:
  2002. ERR_FAIL_V_MSG(nullptr, "Undefined local found.");
  2003. }
  2004. }
  2005. return identifier;
  2006. }
  2007. GDScriptParser::LiteralNode *GDScriptParser::parse_literal() {
  2008. return static_cast<LiteralNode *>(parse_literal(nullptr, false));
  2009. }
  2010. GDScriptParser::ExpressionNode *GDScriptParser::parse_literal(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2011. if (previous.type != GDScriptTokenizer::Token::LITERAL) {
  2012. push_error("Parser bug: parsing literal node without literal token.");
  2013. ERR_FAIL_V_MSG(nullptr, "Parser bug: parsing literal node without literal token.");
  2014. }
  2015. LiteralNode *literal = alloc_node<LiteralNode>();
  2016. complete_extents(literal);
  2017. literal->value = previous.literal;
  2018. return literal;
  2019. }
  2020. GDScriptParser::ExpressionNode *GDScriptParser::parse_self(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2021. if (current_function && current_function->is_static) {
  2022. push_error(R"(Cannot use "self" inside a static function.)");
  2023. }
  2024. SelfNode *self = alloc_node<SelfNode>();
  2025. complete_extents(self);
  2026. self->current_class = current_class;
  2027. return self;
  2028. }
  2029. GDScriptParser::ExpressionNode *GDScriptParser::parse_builtin_constant(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2030. GDScriptTokenizer::Token::Type op_type = previous.type;
  2031. LiteralNode *constant = alloc_node<LiteralNode>();
  2032. complete_extents(constant);
  2033. switch (op_type) {
  2034. case GDScriptTokenizer::Token::CONST_PI:
  2035. constant->value = Math_PI;
  2036. break;
  2037. case GDScriptTokenizer::Token::CONST_TAU:
  2038. constant->value = Math_TAU;
  2039. break;
  2040. case GDScriptTokenizer::Token::CONST_INF:
  2041. constant->value = INFINITY;
  2042. break;
  2043. case GDScriptTokenizer::Token::CONST_NAN:
  2044. constant->value = NAN;
  2045. break;
  2046. default:
  2047. return nullptr; // Unreachable.
  2048. }
  2049. return constant;
  2050. }
  2051. GDScriptParser::ExpressionNode *GDScriptParser::parse_unary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2052. GDScriptTokenizer::Token::Type op_type = previous.type;
  2053. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  2054. switch (op_type) {
  2055. case GDScriptTokenizer::Token::MINUS:
  2056. operation->operation = UnaryOpNode::OP_NEGATIVE;
  2057. operation->variant_op = Variant::OP_NEGATE;
  2058. operation->operand = parse_precedence(PREC_SIGN, false);
  2059. if (operation->operand == nullptr) {
  2060. push_error(R"(Expected expression after "-" operator.)");
  2061. }
  2062. break;
  2063. case GDScriptTokenizer::Token::PLUS:
  2064. operation->operation = UnaryOpNode::OP_POSITIVE;
  2065. operation->variant_op = Variant::OP_POSITIVE;
  2066. operation->operand = parse_precedence(PREC_SIGN, false);
  2067. if (operation->operand == nullptr) {
  2068. push_error(R"(Expected expression after "+" operator.)");
  2069. }
  2070. break;
  2071. case GDScriptTokenizer::Token::TILDE:
  2072. operation->operation = UnaryOpNode::OP_COMPLEMENT;
  2073. operation->variant_op = Variant::OP_BIT_NEGATE;
  2074. operation->operand = parse_precedence(PREC_BIT_NOT, false);
  2075. if (operation->operand == nullptr) {
  2076. push_error(R"(Expected expression after "~" operator.)");
  2077. }
  2078. break;
  2079. case GDScriptTokenizer::Token::NOT:
  2080. case GDScriptTokenizer::Token::BANG:
  2081. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  2082. operation->variant_op = Variant::OP_NOT;
  2083. operation->operand = parse_precedence(PREC_LOGIC_NOT, false);
  2084. if (operation->operand == nullptr) {
  2085. push_error(vformat(R"(Expected expression after "%s" operator.)", op_type == GDScriptTokenizer::Token::NOT ? "not" : "!"));
  2086. }
  2087. break;
  2088. default:
  2089. complete_extents(operation);
  2090. return nullptr; // Unreachable.
  2091. }
  2092. complete_extents(operation);
  2093. return operation;
  2094. }
  2095. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_not_in_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2096. // check that NOT is followed by IN by consuming it before calling parse_binary_operator which will only receive a plain IN
  2097. UnaryOpNode *operation = alloc_node<UnaryOpNode>();
  2098. reset_extents(operation, p_previous_operand);
  2099. update_extents(operation);
  2100. consume(GDScriptTokenizer::Token::IN, R"(Expected "in" after "not" in content-test operator.)");
  2101. ExpressionNode *in_operation = parse_binary_operator(p_previous_operand, p_can_assign);
  2102. operation->operation = UnaryOpNode::OP_LOGIC_NOT;
  2103. operation->variant_op = Variant::OP_NOT;
  2104. operation->operand = in_operation;
  2105. complete_extents(operation);
  2106. return operation;
  2107. }
  2108. GDScriptParser::ExpressionNode *GDScriptParser::parse_binary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2109. GDScriptTokenizer::Token op = previous;
  2110. BinaryOpNode *operation = alloc_node<BinaryOpNode>();
  2111. reset_extents(operation, p_previous_operand);
  2112. update_extents(operation);
  2113. Precedence precedence = (Precedence)(get_rule(op.type)->precedence + 1);
  2114. operation->left_operand = p_previous_operand;
  2115. operation->right_operand = parse_precedence(precedence, false);
  2116. complete_extents(operation);
  2117. if (operation->right_operand == nullptr) {
  2118. push_error(vformat(R"(Expected expression after "%s" operator.")", op.get_name()));
  2119. }
  2120. // TODO: Also for unary, ternary, and assignment.
  2121. switch (op.type) {
  2122. case GDScriptTokenizer::Token::PLUS:
  2123. operation->operation = BinaryOpNode::OP_ADDITION;
  2124. operation->variant_op = Variant::OP_ADD;
  2125. break;
  2126. case GDScriptTokenizer::Token::MINUS:
  2127. operation->operation = BinaryOpNode::OP_SUBTRACTION;
  2128. operation->variant_op = Variant::OP_SUBTRACT;
  2129. break;
  2130. case GDScriptTokenizer::Token::STAR:
  2131. operation->operation = BinaryOpNode::OP_MULTIPLICATION;
  2132. operation->variant_op = Variant::OP_MULTIPLY;
  2133. break;
  2134. case GDScriptTokenizer::Token::SLASH:
  2135. operation->operation = BinaryOpNode::OP_DIVISION;
  2136. operation->variant_op = Variant::OP_DIVIDE;
  2137. break;
  2138. case GDScriptTokenizer::Token::PERCENT:
  2139. operation->operation = BinaryOpNode::OP_MODULO;
  2140. operation->variant_op = Variant::OP_MODULE;
  2141. break;
  2142. case GDScriptTokenizer::Token::STAR_STAR:
  2143. operation->operation = BinaryOpNode::OP_POWER;
  2144. operation->variant_op = Variant::OP_POWER;
  2145. break;
  2146. case GDScriptTokenizer::Token::LESS_LESS:
  2147. operation->operation = BinaryOpNode::OP_BIT_LEFT_SHIFT;
  2148. operation->variant_op = Variant::OP_SHIFT_LEFT;
  2149. break;
  2150. case GDScriptTokenizer::Token::GREATER_GREATER:
  2151. operation->operation = BinaryOpNode::OP_BIT_RIGHT_SHIFT;
  2152. operation->variant_op = Variant::OP_SHIFT_RIGHT;
  2153. break;
  2154. case GDScriptTokenizer::Token::AMPERSAND:
  2155. operation->operation = BinaryOpNode::OP_BIT_AND;
  2156. operation->variant_op = Variant::OP_BIT_AND;
  2157. break;
  2158. case GDScriptTokenizer::Token::PIPE:
  2159. operation->operation = BinaryOpNode::OP_BIT_OR;
  2160. operation->variant_op = Variant::OP_BIT_OR;
  2161. break;
  2162. case GDScriptTokenizer::Token::CARET:
  2163. operation->operation = BinaryOpNode::OP_BIT_XOR;
  2164. operation->variant_op = Variant::OP_BIT_XOR;
  2165. break;
  2166. case GDScriptTokenizer::Token::AND:
  2167. case GDScriptTokenizer::Token::AMPERSAND_AMPERSAND:
  2168. operation->operation = BinaryOpNode::OP_LOGIC_AND;
  2169. operation->variant_op = Variant::OP_AND;
  2170. break;
  2171. case GDScriptTokenizer::Token::OR:
  2172. case GDScriptTokenizer::Token::PIPE_PIPE:
  2173. operation->operation = BinaryOpNode::OP_LOGIC_OR;
  2174. operation->variant_op = Variant::OP_OR;
  2175. break;
  2176. case GDScriptTokenizer::Token::IN:
  2177. operation->operation = BinaryOpNode::OP_CONTENT_TEST;
  2178. operation->variant_op = Variant::OP_IN;
  2179. break;
  2180. case GDScriptTokenizer::Token::EQUAL_EQUAL:
  2181. operation->operation = BinaryOpNode::OP_COMP_EQUAL;
  2182. operation->variant_op = Variant::OP_EQUAL;
  2183. break;
  2184. case GDScriptTokenizer::Token::BANG_EQUAL:
  2185. operation->operation = BinaryOpNode::OP_COMP_NOT_EQUAL;
  2186. operation->variant_op = Variant::OP_NOT_EQUAL;
  2187. break;
  2188. case GDScriptTokenizer::Token::LESS:
  2189. operation->operation = BinaryOpNode::OP_COMP_LESS;
  2190. operation->variant_op = Variant::OP_LESS;
  2191. break;
  2192. case GDScriptTokenizer::Token::LESS_EQUAL:
  2193. operation->operation = BinaryOpNode::OP_COMP_LESS_EQUAL;
  2194. operation->variant_op = Variant::OP_LESS_EQUAL;
  2195. break;
  2196. case GDScriptTokenizer::Token::GREATER:
  2197. operation->operation = BinaryOpNode::OP_COMP_GREATER;
  2198. operation->variant_op = Variant::OP_GREATER;
  2199. break;
  2200. case GDScriptTokenizer::Token::GREATER_EQUAL:
  2201. operation->operation = BinaryOpNode::OP_COMP_GREATER_EQUAL;
  2202. operation->variant_op = Variant::OP_GREATER_EQUAL;
  2203. break;
  2204. default:
  2205. return nullptr; // Unreachable.
  2206. }
  2207. return operation;
  2208. }
  2209. GDScriptParser::ExpressionNode *GDScriptParser::parse_ternary_operator(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2210. // Only one ternary operation exists, so no abstraction here.
  2211. TernaryOpNode *operation = alloc_node<TernaryOpNode>();
  2212. reset_extents(operation, p_previous_operand);
  2213. update_extents(operation);
  2214. operation->true_expr = p_previous_operand;
  2215. operation->condition = parse_precedence(PREC_TERNARY, false);
  2216. if (operation->condition == nullptr) {
  2217. push_error(R"(Expected expression as ternary condition after "if".)");
  2218. }
  2219. consume(GDScriptTokenizer::Token::ELSE, R"(Expected "else" after ternary operator condition.)");
  2220. operation->false_expr = parse_precedence(PREC_TERNARY, false);
  2221. if (operation->false_expr == nullptr) {
  2222. push_error(R"(Expected expression after "else".)");
  2223. }
  2224. complete_extents(operation);
  2225. return operation;
  2226. }
  2227. GDScriptParser::ExpressionNode *GDScriptParser::parse_assignment(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2228. if (!p_can_assign) {
  2229. push_error("Assignment is not allowed inside an expression.");
  2230. return parse_expression(false); // Return the following expression.
  2231. }
  2232. if (p_previous_operand == nullptr) {
  2233. return parse_expression(false); // Return the following expression.
  2234. }
  2235. #ifdef DEBUG_ENABLED
  2236. VariableNode *source_variable = nullptr;
  2237. #endif
  2238. switch (p_previous_operand->type) {
  2239. case Node::IDENTIFIER: {
  2240. #ifdef DEBUG_ENABLED
  2241. // Get source to store assignment count.
  2242. // Also remove one usage since assignment isn't usage.
  2243. IdentifierNode *id = static_cast<IdentifierNode *>(p_previous_operand);
  2244. switch (id->source) {
  2245. case IdentifierNode::LOCAL_VARIABLE:
  2246. source_variable = id->variable_source;
  2247. id->variable_source->usages--;
  2248. break;
  2249. case IdentifierNode::LOCAL_CONSTANT:
  2250. id->constant_source->usages--;
  2251. break;
  2252. case IdentifierNode::FUNCTION_PARAMETER:
  2253. id->parameter_source->usages--;
  2254. break;
  2255. case IdentifierNode::LOCAL_ITERATOR:
  2256. case IdentifierNode::LOCAL_BIND:
  2257. id->bind_source->usages--;
  2258. break;
  2259. default:
  2260. break;
  2261. }
  2262. #endif
  2263. } break;
  2264. case Node::SUBSCRIPT:
  2265. // Okay.
  2266. break;
  2267. default:
  2268. push_error(R"(Only identifier, attribute access, and subscription access can be used as assignment target.)");
  2269. return parse_expression(false); // Return the following expression.
  2270. }
  2271. AssignmentNode *assignment = alloc_node<AssignmentNode>();
  2272. reset_extents(assignment, p_previous_operand);
  2273. update_extents(assignment);
  2274. make_completion_context(COMPLETION_ASSIGN, assignment);
  2275. #ifdef DEBUG_ENABLED
  2276. bool has_operator = true;
  2277. #endif
  2278. switch (previous.type) {
  2279. case GDScriptTokenizer::Token::EQUAL:
  2280. assignment->operation = AssignmentNode::OP_NONE;
  2281. assignment->variant_op = Variant::OP_MAX;
  2282. #ifdef DEBUG_ENABLED
  2283. has_operator = false;
  2284. #endif
  2285. break;
  2286. case GDScriptTokenizer::Token::PLUS_EQUAL:
  2287. assignment->operation = AssignmentNode::OP_ADDITION;
  2288. assignment->variant_op = Variant::OP_ADD;
  2289. break;
  2290. case GDScriptTokenizer::Token::MINUS_EQUAL:
  2291. assignment->operation = AssignmentNode::OP_SUBTRACTION;
  2292. assignment->variant_op = Variant::OP_SUBTRACT;
  2293. break;
  2294. case GDScriptTokenizer::Token::STAR_EQUAL:
  2295. assignment->operation = AssignmentNode::OP_MULTIPLICATION;
  2296. assignment->variant_op = Variant::OP_MULTIPLY;
  2297. break;
  2298. case GDScriptTokenizer::Token::STAR_STAR_EQUAL:
  2299. assignment->operation = AssignmentNode::OP_POWER;
  2300. assignment->variant_op = Variant::OP_POWER;
  2301. break;
  2302. case GDScriptTokenizer::Token::SLASH_EQUAL:
  2303. assignment->operation = AssignmentNode::OP_DIVISION;
  2304. assignment->variant_op = Variant::OP_DIVIDE;
  2305. break;
  2306. case GDScriptTokenizer::Token::PERCENT_EQUAL:
  2307. assignment->operation = AssignmentNode::OP_MODULO;
  2308. assignment->variant_op = Variant::OP_MODULE;
  2309. break;
  2310. case GDScriptTokenizer::Token::LESS_LESS_EQUAL:
  2311. assignment->operation = AssignmentNode::OP_BIT_SHIFT_LEFT;
  2312. assignment->variant_op = Variant::OP_SHIFT_LEFT;
  2313. break;
  2314. case GDScriptTokenizer::Token::GREATER_GREATER_EQUAL:
  2315. assignment->operation = AssignmentNode::OP_BIT_SHIFT_RIGHT;
  2316. assignment->variant_op = Variant::OP_SHIFT_RIGHT;
  2317. break;
  2318. case GDScriptTokenizer::Token::AMPERSAND_EQUAL:
  2319. assignment->operation = AssignmentNode::OP_BIT_AND;
  2320. assignment->variant_op = Variant::OP_BIT_AND;
  2321. break;
  2322. case GDScriptTokenizer::Token::PIPE_EQUAL:
  2323. assignment->operation = AssignmentNode::OP_BIT_OR;
  2324. assignment->variant_op = Variant::OP_BIT_OR;
  2325. break;
  2326. case GDScriptTokenizer::Token::CARET_EQUAL:
  2327. assignment->operation = AssignmentNode::OP_BIT_XOR;
  2328. assignment->variant_op = Variant::OP_BIT_XOR;
  2329. break;
  2330. default:
  2331. break; // Unreachable.
  2332. }
  2333. assignment->assignee = p_previous_operand;
  2334. assignment->assigned_value = parse_expression(false);
  2335. if (assignment->assigned_value == nullptr) {
  2336. push_error(R"(Expected an expression after "=".)");
  2337. }
  2338. complete_extents(assignment);
  2339. #ifdef DEBUG_ENABLED
  2340. if (source_variable != nullptr) {
  2341. if (has_operator && source_variable->assignments == 0) {
  2342. push_warning(assignment, GDScriptWarning::UNASSIGNED_VARIABLE_OP_ASSIGN, source_variable->identifier->name);
  2343. }
  2344. source_variable->assignments += 1;
  2345. }
  2346. #endif
  2347. return assignment;
  2348. }
  2349. GDScriptParser::ExpressionNode *GDScriptParser::parse_await(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2350. AwaitNode *await = alloc_node<AwaitNode>();
  2351. ExpressionNode *element = parse_precedence(PREC_AWAIT, false);
  2352. if (element == nullptr) {
  2353. push_error(R"(Expected signal or coroutine after "await".)");
  2354. }
  2355. await->to_await = element;
  2356. complete_extents(await);
  2357. if (current_function) { // Might be null in a getter or setter.
  2358. current_function->is_coroutine = true;
  2359. }
  2360. return await;
  2361. }
  2362. GDScriptParser::ExpressionNode *GDScriptParser::parse_array(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2363. ArrayNode *array = alloc_node<ArrayNode>();
  2364. if (!check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2365. do {
  2366. if (check(GDScriptTokenizer::Token::BRACKET_CLOSE)) {
  2367. // Allow for trailing comma.
  2368. break;
  2369. }
  2370. ExpressionNode *element = parse_expression(false);
  2371. if (element == nullptr) {
  2372. push_error(R"(Expected expression as array element.)");
  2373. } else {
  2374. array->elements.push_back(element);
  2375. }
  2376. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2377. }
  2378. pop_multiline();
  2379. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after array elements.)");
  2380. complete_extents(array);
  2381. return array;
  2382. }
  2383. GDScriptParser::ExpressionNode *GDScriptParser::parse_dictionary(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2384. DictionaryNode *dictionary = alloc_node<DictionaryNode>();
  2385. bool decided_style = false;
  2386. if (!check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2387. do {
  2388. if (check(GDScriptTokenizer::Token::BRACE_CLOSE)) {
  2389. // Allow for trailing comma.
  2390. break;
  2391. }
  2392. // Key.
  2393. ExpressionNode *key = parse_expression(false, true); // Stop on "=" so we can check for Lua table style.
  2394. if (key == nullptr) {
  2395. push_error(R"(Expected expression as dictionary key.)");
  2396. }
  2397. if (!decided_style) {
  2398. switch (current.type) {
  2399. case GDScriptTokenizer::Token::COLON:
  2400. dictionary->style = DictionaryNode::PYTHON_DICT;
  2401. break;
  2402. case GDScriptTokenizer::Token::EQUAL:
  2403. dictionary->style = DictionaryNode::LUA_TABLE;
  2404. break;
  2405. default:
  2406. push_error(R"(Expected ":" or "=" after dictionary key.)");
  2407. break;
  2408. }
  2409. decided_style = true;
  2410. }
  2411. switch (dictionary->style) {
  2412. case DictionaryNode::LUA_TABLE:
  2413. if (key != nullptr && key->type != Node::IDENTIFIER && key->type != Node::LITERAL) {
  2414. push_error("Expected identifier or string as LUA-style dictionary key.");
  2415. advance();
  2416. break;
  2417. }
  2418. if (key != nullptr && key->type == Node::LITERAL && static_cast<LiteralNode *>(key)->value.get_type() != Variant::STRING) {
  2419. push_error("Expected identifier or string as LUA-style dictionary key.");
  2420. advance();
  2421. break;
  2422. }
  2423. if (!match(GDScriptTokenizer::Token::EQUAL)) {
  2424. if (match(GDScriptTokenizer::Token::COLON)) {
  2425. push_error(R"(Expected "=" after dictionary key. Mixing dictionary styles is not allowed.)");
  2426. advance(); // Consume wrong separator anyway.
  2427. } else {
  2428. push_error(R"(Expected "=" after dictionary key.)");
  2429. }
  2430. }
  2431. if (key != nullptr) {
  2432. key->is_constant = true;
  2433. if (key->type == Node::IDENTIFIER) {
  2434. key->reduced_value = static_cast<IdentifierNode *>(key)->name;
  2435. } else if (key->type == Node::LITERAL) {
  2436. key->reduced_value = StringName(static_cast<LiteralNode *>(key)->value.operator String());
  2437. }
  2438. }
  2439. break;
  2440. case DictionaryNode::PYTHON_DICT:
  2441. if (!match(GDScriptTokenizer::Token::COLON)) {
  2442. if (match(GDScriptTokenizer::Token::EQUAL)) {
  2443. push_error(R"(Expected ":" after dictionary key. Mixing dictionary styles is not allowed.)");
  2444. advance(); // Consume wrong separator anyway.
  2445. } else {
  2446. push_error(R"(Expected ":" after dictionary key.)");
  2447. }
  2448. }
  2449. break;
  2450. }
  2451. // Value.
  2452. ExpressionNode *value = parse_expression(false);
  2453. if (value == nullptr) {
  2454. push_error(R"(Expected expression as dictionary value.)");
  2455. }
  2456. if (key != nullptr && value != nullptr) {
  2457. dictionary->elements.push_back({ key, value });
  2458. }
  2459. } while (match(GDScriptTokenizer::Token::COMMA) && !is_at_end());
  2460. }
  2461. pop_multiline();
  2462. consume(GDScriptTokenizer::Token::BRACE_CLOSE, R"(Expected closing "}" after dictionary elements.)");
  2463. complete_extents(dictionary);
  2464. return dictionary;
  2465. }
  2466. GDScriptParser::ExpressionNode *GDScriptParser::parse_grouping(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2467. ExpressionNode *grouped = parse_expression(false);
  2468. pop_multiline();
  2469. if (grouped == nullptr) {
  2470. push_error(R"(Expected grouping expression.)");
  2471. } else {
  2472. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after grouping expression.)*");
  2473. }
  2474. return grouped;
  2475. }
  2476. GDScriptParser::ExpressionNode *GDScriptParser::parse_attribute(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2477. SubscriptNode *attribute = alloc_node<SubscriptNode>();
  2478. reset_extents(attribute, p_previous_operand);
  2479. update_extents(attribute);
  2480. if (for_completion) {
  2481. bool is_builtin = false;
  2482. if (p_previous_operand && p_previous_operand->type == Node::IDENTIFIER) {
  2483. const IdentifierNode *id = static_cast<const IdentifierNode *>(p_previous_operand);
  2484. Variant::Type builtin_type = get_builtin_type(id->name);
  2485. if (builtin_type < Variant::VARIANT_MAX) {
  2486. make_completion_context(COMPLETION_BUILT_IN_TYPE_CONSTANT_OR_STATIC_METHOD, builtin_type, true);
  2487. is_builtin = true;
  2488. }
  2489. }
  2490. if (!is_builtin) {
  2491. make_completion_context(COMPLETION_ATTRIBUTE, attribute, -1, true);
  2492. }
  2493. }
  2494. attribute->base = p_previous_operand;
  2495. if (current.is_node_name()) {
  2496. current.type = GDScriptTokenizer::Token::IDENTIFIER;
  2497. }
  2498. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected identifier after "." for attribute access.)")) {
  2499. complete_extents(attribute);
  2500. return attribute;
  2501. }
  2502. attribute->is_attribute = true;
  2503. attribute->attribute = parse_identifier();
  2504. complete_extents(attribute);
  2505. return attribute;
  2506. }
  2507. GDScriptParser::ExpressionNode *GDScriptParser::parse_subscript(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2508. SubscriptNode *subscript = alloc_node<SubscriptNode>();
  2509. reset_extents(subscript, p_previous_operand);
  2510. update_extents(subscript);
  2511. make_completion_context(COMPLETION_SUBSCRIPT, subscript);
  2512. subscript->base = p_previous_operand;
  2513. subscript->index = parse_expression(false);
  2514. if (subscript->index == nullptr) {
  2515. push_error(R"(Expected expression after "[".)");
  2516. }
  2517. pop_multiline();
  2518. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected "]" after subscription index.)");
  2519. complete_extents(subscript);
  2520. return subscript;
  2521. }
  2522. GDScriptParser::ExpressionNode *GDScriptParser::parse_cast(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2523. CastNode *cast = alloc_node<CastNode>();
  2524. reset_extents(cast, p_previous_operand);
  2525. update_extents(cast);
  2526. cast->operand = p_previous_operand;
  2527. cast->cast_type = parse_type();
  2528. complete_extents(cast);
  2529. if (cast->cast_type == nullptr) {
  2530. push_error(R"(Expected type specifier after "as".)");
  2531. return p_previous_operand;
  2532. }
  2533. return cast;
  2534. }
  2535. GDScriptParser::ExpressionNode *GDScriptParser::parse_call(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2536. CallNode *call = alloc_node<CallNode>();
  2537. reset_extents(call, p_previous_operand);
  2538. if (previous.type == GDScriptTokenizer::Token::SUPER) {
  2539. // Super call.
  2540. call->is_super = true;
  2541. push_multiline(true);
  2542. if (match(GDScriptTokenizer::Token::PARENTHESIS_OPEN)) {
  2543. // Implicit call to the parent method of the same name.
  2544. if (current_function == nullptr) {
  2545. push_error(R"(Cannot use implicit "super" call outside of a function.)");
  2546. pop_multiline();
  2547. complete_extents(call);
  2548. return nullptr;
  2549. }
  2550. if (current_function->identifier) {
  2551. call->function_name = current_function->identifier->name;
  2552. } else {
  2553. call->function_name = SNAME("<anonymous>");
  2554. }
  2555. } else {
  2556. consume(GDScriptTokenizer::Token::PERIOD, R"(Expected "." or "(" after "super".)");
  2557. make_completion_context(COMPLETION_SUPER_METHOD, call, true);
  2558. if (!consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected function name after ".".)")) {
  2559. pop_multiline();
  2560. complete_extents(call);
  2561. return nullptr;
  2562. }
  2563. IdentifierNode *identifier = parse_identifier();
  2564. call->callee = identifier;
  2565. call->function_name = identifier->name;
  2566. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after function name.)");
  2567. }
  2568. } else {
  2569. call->callee = p_previous_operand;
  2570. if (call->callee == nullptr) {
  2571. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2572. } else if (call->callee->type == Node::IDENTIFIER) {
  2573. call->function_name = static_cast<IdentifierNode *>(call->callee)->name;
  2574. make_completion_context(COMPLETION_METHOD, call->callee);
  2575. } else if (call->callee->type == Node::SUBSCRIPT) {
  2576. SubscriptNode *attribute = static_cast<SubscriptNode *>(call->callee);
  2577. if (attribute->is_attribute) {
  2578. if (attribute->attribute) {
  2579. call->function_name = attribute->attribute->name;
  2580. }
  2581. make_completion_context(COMPLETION_ATTRIBUTE_METHOD, call->callee);
  2582. } else {
  2583. // TODO: The analyzer can see if this is actually a Callable and give better error message.
  2584. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2585. }
  2586. } else {
  2587. push_error(R"*(Cannot call on an expression. Use ".call()" if it's a Callable.)*");
  2588. }
  2589. }
  2590. // Arguments.
  2591. CompletionType ct = COMPLETION_CALL_ARGUMENTS;
  2592. if (call->function_name == SNAME("load")) {
  2593. ct = COMPLETION_RESOURCE_PATH;
  2594. }
  2595. push_completion_call(call);
  2596. int argument_index = 0;
  2597. do {
  2598. make_completion_context(ct, call, argument_index++, true);
  2599. if (check(GDScriptTokenizer::Token::PARENTHESIS_CLOSE)) {
  2600. // Allow for trailing comma.
  2601. break;
  2602. }
  2603. bool use_identifier_completion = current.cursor_place == GDScriptTokenizer::CURSOR_END || current.cursor_place == GDScriptTokenizer::CURSOR_MIDDLE;
  2604. ExpressionNode *argument = parse_expression(false);
  2605. if (argument == nullptr) {
  2606. push_error(R"(Expected expression as the function argument.)");
  2607. } else {
  2608. call->arguments.push_back(argument);
  2609. if (argument->type == Node::IDENTIFIER && use_identifier_completion) {
  2610. completion_context.type = COMPLETION_IDENTIFIER;
  2611. }
  2612. }
  2613. ct = COMPLETION_CALL_ARGUMENTS;
  2614. } while (match(GDScriptTokenizer::Token::COMMA));
  2615. pop_completion_call();
  2616. pop_multiline();
  2617. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected closing ")" after call arguments.)*");
  2618. complete_extents(call);
  2619. return call;
  2620. }
  2621. GDScriptParser::ExpressionNode *GDScriptParser::parse_get_node(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2622. if (!current.is_node_name() && !check(GDScriptTokenizer::Token::LITERAL) && !check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
  2623. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
  2624. return nullptr;
  2625. }
  2626. if (check(GDScriptTokenizer::Token::LITERAL)) {
  2627. if (current.literal.get_type() != Variant::STRING) {
  2628. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous.get_name()));
  2629. return nullptr;
  2630. }
  2631. }
  2632. GetNodeNode *get_node = alloc_node<GetNodeNode>();
  2633. // Store the last item in the path so the parser knows what to expect.
  2634. // Allow allows more specific error messages.
  2635. enum PathState {
  2636. PATH_STATE_START,
  2637. PATH_STATE_SLASH,
  2638. PATH_STATE_PERCENT,
  2639. PATH_STATE_NODE_NAME,
  2640. } path_state = PATH_STATE_START;
  2641. if (previous.type == GDScriptTokenizer::Token::DOLLAR) {
  2642. // Detect initial slash, which will be handled in the loop if it matches.
  2643. match(GDScriptTokenizer::Token::SLASH);
  2644. #ifdef DEBUG_ENABLED
  2645. } else {
  2646. get_node->use_dollar = false;
  2647. #endif
  2648. }
  2649. int context_argument = 0;
  2650. do {
  2651. if (previous.type == GDScriptTokenizer::Token::PERCENT) {
  2652. if (path_state != PATH_STATE_START && path_state != PATH_STATE_SLASH) {
  2653. push_error(R"("%" is only valid in the beginning of a node name (either after "$" or after "/"))");
  2654. complete_extents(get_node);
  2655. return nullptr;
  2656. }
  2657. get_node->full_path += "%";
  2658. path_state = PATH_STATE_PERCENT;
  2659. } else if (previous.type == GDScriptTokenizer::Token::SLASH) {
  2660. if (path_state != PATH_STATE_START && path_state != PATH_STATE_NODE_NAME) {
  2661. push_error(R"("/" is only valid at the beginning of the path or after a node name.)");
  2662. complete_extents(get_node);
  2663. return nullptr;
  2664. }
  2665. get_node->full_path += "/";
  2666. path_state = PATH_STATE_SLASH;
  2667. }
  2668. make_completion_context(COMPLETION_GET_NODE, get_node, context_argument++);
  2669. if (match(GDScriptTokenizer::Token::LITERAL)) {
  2670. if (previous.literal.get_type() != Variant::STRING) {
  2671. String previous_token;
  2672. switch (path_state) {
  2673. case PATH_STATE_START:
  2674. previous_token = "$";
  2675. break;
  2676. case PATH_STATE_PERCENT:
  2677. previous_token = "%";
  2678. break;
  2679. case PATH_STATE_SLASH:
  2680. previous_token = "/";
  2681. break;
  2682. default:
  2683. break;
  2684. }
  2685. push_error(vformat(R"(Expected node path as string or identifier after "%s".)", previous_token));
  2686. complete_extents(get_node);
  2687. return nullptr;
  2688. }
  2689. get_node->full_path += previous.literal.operator String();
  2690. path_state = PATH_STATE_NODE_NAME;
  2691. } else if (current.is_node_name()) {
  2692. advance();
  2693. String identifier = previous.get_identifier();
  2694. #ifdef DEBUG_ENABLED
  2695. // Check spoofing.
  2696. if (TS->has_feature(TextServer::FEATURE_UNICODE_SECURITY) && TS->spoof_check(identifier)) {
  2697. push_warning(get_node, GDScriptWarning::CONFUSABLE_IDENTIFIER, identifier);
  2698. }
  2699. #endif
  2700. get_node->full_path += identifier;
  2701. path_state = PATH_STATE_NODE_NAME;
  2702. } else if (!check(GDScriptTokenizer::Token::SLASH) && !check(GDScriptTokenizer::Token::PERCENT)) {
  2703. push_error(vformat(R"(Unexpected "%s" in node path.)", current.get_name()));
  2704. complete_extents(get_node);
  2705. return nullptr;
  2706. }
  2707. } while (match(GDScriptTokenizer::Token::SLASH) || match(GDScriptTokenizer::Token::PERCENT));
  2708. complete_extents(get_node);
  2709. return get_node;
  2710. }
  2711. GDScriptParser::ExpressionNode *GDScriptParser::parse_preload(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2712. PreloadNode *preload = alloc_node<PreloadNode>();
  2713. preload->resolved_path = "<missing path>";
  2714. push_multiline(true);
  2715. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected "(" after "preload".)");
  2716. make_completion_context(COMPLETION_RESOURCE_PATH, preload);
  2717. push_completion_call(preload);
  2718. preload->path = parse_expression(false);
  2719. if (preload->path == nullptr) {
  2720. push_error(R"(Expected resource path after "(".)");
  2721. }
  2722. pop_completion_call();
  2723. pop_multiline();
  2724. consume(GDScriptTokenizer::Token::PARENTHESIS_CLOSE, R"*(Expected ")" after preload path.)*");
  2725. complete_extents(preload);
  2726. return preload;
  2727. }
  2728. GDScriptParser::ExpressionNode *GDScriptParser::parse_lambda(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2729. LambdaNode *lambda = alloc_node<LambdaNode>();
  2730. lambda->parent_function = current_function;
  2731. FunctionNode *function = alloc_node<FunctionNode>();
  2732. function->source_lambda = lambda;
  2733. function->is_static = current_function != nullptr ? current_function->is_static : false;
  2734. if (match(GDScriptTokenizer::Token::IDENTIFIER)) {
  2735. function->identifier = parse_identifier();
  2736. }
  2737. bool multiline_context = multiline_stack.back()->get();
  2738. // Reset the multiline stack since we don't want the multiline mode one in the lambda body.
  2739. push_multiline(false);
  2740. if (multiline_context) {
  2741. tokenizer.push_expression_indented_block();
  2742. }
  2743. push_multiline(true); // For the parameters.
  2744. if (function->identifier) {
  2745. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after lambda name.)");
  2746. } else {
  2747. consume(GDScriptTokenizer::Token::PARENTHESIS_OPEN, R"(Expected opening "(" after "func".)");
  2748. }
  2749. FunctionNode *previous_function = current_function;
  2750. current_function = function;
  2751. SuiteNode *body = alloc_node<SuiteNode>();
  2752. body->parent_function = current_function;
  2753. body->parent_block = current_suite;
  2754. SuiteNode *previous_suite = current_suite;
  2755. current_suite = body;
  2756. parse_function_signature(function, body, "lambda");
  2757. current_suite = previous_suite;
  2758. bool previous_in_lambda = in_lambda;
  2759. in_lambda = true;
  2760. // Save break/continue state.
  2761. bool could_break = can_break;
  2762. bool could_continue = can_continue;
  2763. // Disallow break/continue.
  2764. can_break = false;
  2765. can_continue = false;
  2766. function->body = parse_suite("lambda declaration", body, true);
  2767. complete_extents(function);
  2768. complete_extents(lambda);
  2769. pop_multiline();
  2770. if (multiline_context) {
  2771. // If we're in multiline mode, we want to skip the spurious DEDENT and NEWLINE tokens.
  2772. while (check(GDScriptTokenizer::Token::DEDENT) || check(GDScriptTokenizer::Token::INDENT) || check(GDScriptTokenizer::Token::NEWLINE)) {
  2773. current = tokenizer.scan(); // Not advance() since we don't want to change the previous token.
  2774. }
  2775. tokenizer.pop_expression_indented_block();
  2776. }
  2777. current_function = previous_function;
  2778. in_lambda = previous_in_lambda;
  2779. lambda->function = function;
  2780. // Reset break/continue state.
  2781. can_break = could_break;
  2782. can_continue = could_continue;
  2783. return lambda;
  2784. }
  2785. GDScriptParser::ExpressionNode *GDScriptParser::parse_type_test(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2786. TypeTestNode *type_test = alloc_node<TypeTestNode>();
  2787. reset_extents(type_test, p_previous_operand);
  2788. update_extents(type_test);
  2789. type_test->operand = p_previous_operand;
  2790. type_test->test_type = parse_type();
  2791. complete_extents(type_test);
  2792. if (type_test->test_type == nullptr) {
  2793. push_error(R"(Expected type specifier after "is".)");
  2794. }
  2795. return type_test;
  2796. }
  2797. GDScriptParser::ExpressionNode *GDScriptParser::parse_yield(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2798. push_error(R"("yield" was removed in Godot 4.0. Use "await" instead.)");
  2799. return nullptr;
  2800. }
  2801. GDScriptParser::ExpressionNode *GDScriptParser::parse_invalid_token(ExpressionNode *p_previous_operand, bool p_can_assign) {
  2802. // Just for better error messages.
  2803. GDScriptTokenizer::Token::Type invalid = previous.type;
  2804. switch (invalid) {
  2805. case GDScriptTokenizer::Token::QUESTION_MARK:
  2806. push_error(R"(Unexpected "?" in source. If you want a ternary operator, use "truthy_value if true_condition else falsy_value".)");
  2807. break;
  2808. default:
  2809. return nullptr; // Unreachable.
  2810. }
  2811. // Return the previous expression.
  2812. return p_previous_operand;
  2813. }
  2814. GDScriptParser::TypeNode *GDScriptParser::parse_type(bool p_allow_void) {
  2815. TypeNode *type = alloc_node<TypeNode>();
  2816. make_completion_context(p_allow_void ? COMPLETION_TYPE_NAME_OR_VOID : COMPLETION_TYPE_NAME, type);
  2817. if (!match(GDScriptTokenizer::Token::IDENTIFIER)) {
  2818. if (match(GDScriptTokenizer::Token::VOID)) {
  2819. if (p_allow_void) {
  2820. complete_extents(type);
  2821. TypeNode *void_type = type;
  2822. return void_type;
  2823. } else {
  2824. push_error(R"("void" is only allowed for a function return type.)");
  2825. }
  2826. }
  2827. // Leave error message to the caller who knows the context.
  2828. complete_extents(type);
  2829. return nullptr;
  2830. }
  2831. IdentifierNode *type_element = parse_identifier();
  2832. type->type_chain.push_back(type_element);
  2833. if (match(GDScriptTokenizer::Token::BRACKET_OPEN)) {
  2834. // Typed collection (like Array[int]).
  2835. type->container_type = parse_type(false); // Don't allow void for array element type.
  2836. if (type->container_type == nullptr) {
  2837. push_error(R"(Expected type for collection after "[".)");
  2838. complete_extents(type);
  2839. type = nullptr;
  2840. } else if (type->container_type->container_type != nullptr) {
  2841. push_error("Nested typed collections are not supported.");
  2842. }
  2843. consume(GDScriptTokenizer::Token::BRACKET_CLOSE, R"(Expected closing "]" after collection type.)");
  2844. if (type != nullptr) {
  2845. complete_extents(type);
  2846. }
  2847. return type;
  2848. }
  2849. int chain_index = 1;
  2850. while (match(GDScriptTokenizer::Token::PERIOD)) {
  2851. make_completion_context(COMPLETION_TYPE_ATTRIBUTE, type, chain_index++);
  2852. if (consume(GDScriptTokenizer::Token::IDENTIFIER, R"(Expected inner type name after ".".)")) {
  2853. type_element = parse_identifier();
  2854. type->type_chain.push_back(type_element);
  2855. }
  2856. }
  2857. complete_extents(type);
  2858. return type;
  2859. }
  2860. #ifdef TOOLS_ENABLED
  2861. enum DocLineState {
  2862. DOC_LINE_NORMAL,
  2863. DOC_LINE_IN_CODE,
  2864. DOC_LINE_IN_CODEBLOCK,
  2865. };
  2866. static String _process_doc_line(const String &p_line, const String &p_text, const String &p_space_prefix, DocLineState &r_state) {
  2867. String line = p_line;
  2868. if (r_state == DOC_LINE_NORMAL) {
  2869. line = line.strip_edges(true, false);
  2870. } else {
  2871. line = line.trim_prefix(p_space_prefix);
  2872. }
  2873. String line_join;
  2874. if (!p_text.is_empty()) {
  2875. if (r_state == DOC_LINE_NORMAL) {
  2876. if (p_text.ends_with("[/codeblock]")) {
  2877. line_join = "\n";
  2878. } else if (!p_text.ends_with("[br]")) {
  2879. line_join = " ";
  2880. }
  2881. } else {
  2882. line_join = "\n";
  2883. }
  2884. }
  2885. String result;
  2886. int from = 0;
  2887. int buffer_start = 0;
  2888. const int len = line.length();
  2889. bool process = true;
  2890. while (process) {
  2891. switch (r_state) {
  2892. case DOC_LINE_NORMAL: {
  2893. int lb_pos = line.find_char('[', from);
  2894. if (lb_pos < 0) {
  2895. process = false;
  2896. break;
  2897. }
  2898. int rb_pos = line.find_char(']', lb_pos + 1);
  2899. if (rb_pos < 0) {
  2900. process = false;
  2901. break;
  2902. }
  2903. from = rb_pos + 1;
  2904. String tag = line.substr(lb_pos + 1, rb_pos - lb_pos - 1);
  2905. if (tag == "code") {
  2906. r_state = DOC_LINE_IN_CODE;
  2907. } else if (tag == "codeblock") {
  2908. if (lb_pos == 0) {
  2909. line_join = "\n";
  2910. } else {
  2911. result += line.substr(buffer_start, lb_pos - buffer_start) + '\n';
  2912. }
  2913. result += "[codeblock]";
  2914. if (from < len) {
  2915. result += '\n';
  2916. }
  2917. r_state = DOC_LINE_IN_CODEBLOCK;
  2918. buffer_start = from;
  2919. }
  2920. } break;
  2921. case DOC_LINE_IN_CODE: {
  2922. int pos = line.find("[/code]", from);
  2923. if (pos < 0) {
  2924. process = false;
  2925. break;
  2926. }
  2927. from = pos + 7;
  2928. r_state = DOC_LINE_NORMAL;
  2929. } break;
  2930. case DOC_LINE_IN_CODEBLOCK: {
  2931. int pos = line.find("[/codeblock]", from);
  2932. if (pos < 0) {
  2933. process = false;
  2934. break;
  2935. }
  2936. from = pos + 12;
  2937. if (pos == 0) {
  2938. line_join = "\n";
  2939. } else {
  2940. result += line.substr(buffer_start, pos - buffer_start) + '\n';
  2941. }
  2942. result += "[/codeblock]";
  2943. if (from < len) {
  2944. result += '\n';
  2945. }
  2946. r_state = DOC_LINE_NORMAL;
  2947. buffer_start = from;
  2948. } break;
  2949. }
  2950. }
  2951. result += line.substr(buffer_start);
  2952. if (r_state == DOC_LINE_NORMAL) {
  2953. result = result.strip_edges(false, true);
  2954. }
  2955. return line_join + result;
  2956. }
  2957. bool GDScriptParser::has_comment(int p_line, bool p_must_be_doc) {
  2958. bool has_comment = tokenizer.get_comments().has(p_line);
  2959. // If there are no comments or if we don't care whether the comment
  2960. // is a docstring, we have our result.
  2961. if (!p_must_be_doc || !has_comment) {
  2962. return has_comment;
  2963. }
  2964. return tokenizer.get_comments()[p_line].comment.begins_with("##");
  2965. }
  2966. String GDScriptParser::get_doc_comment(int p_line, bool p_single_line) {
  2967. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer.get_comments();
  2968. ERR_FAIL_COND_V(!comments.has(p_line), String());
  2969. if (p_single_line) {
  2970. if (comments[p_line].comment.begins_with("##")) {
  2971. return comments[p_line].comment.trim_prefix("##").strip_edges();
  2972. }
  2973. return "";
  2974. }
  2975. String doc;
  2976. int line = p_line;
  2977. DocLineState state = DOC_LINE_NORMAL;
  2978. while (comments.has(line - 1)) {
  2979. if (!comments[line - 1].new_line || !comments[line - 1].comment.begins_with("##")) {
  2980. break;
  2981. }
  2982. line--;
  2983. }
  2984. String space_prefix;
  2985. if (comments.has(line) && comments[line].comment.begins_with("##")) {
  2986. int i = 2;
  2987. for (; i < comments[line].comment.length(); i++) {
  2988. if (comments[line].comment[i] != ' ') {
  2989. break;
  2990. }
  2991. }
  2992. space_prefix = String(" ").repeat(i - 2);
  2993. }
  2994. while (comments.has(line)) {
  2995. if (!comments[line].new_line || !comments[line].comment.begins_with("##")) {
  2996. break;
  2997. }
  2998. String doc_line = comments[line].comment.trim_prefix("##");
  2999. doc += _process_doc_line(doc_line, doc, space_prefix, state);
  3000. line++;
  3001. }
  3002. return doc;
  3003. }
  3004. 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) {
  3005. const HashMap<int, GDScriptTokenizer::CommentData> &comments = tokenizer.get_comments();
  3006. if (!comments.has(p_line)) {
  3007. return;
  3008. }
  3009. ERR_FAIL_COND(!p_brief.is_empty() || !p_desc.is_empty() || p_tutorials.size() != 0);
  3010. int line = p_line;
  3011. DocLineState state = DOC_LINE_NORMAL;
  3012. enum Mode {
  3013. BRIEF,
  3014. DESC,
  3015. TUTORIALS,
  3016. DONE,
  3017. };
  3018. Mode mode = BRIEF;
  3019. if (p_inner_class) {
  3020. while (comments.has(line - 1)) {
  3021. if (!comments[line - 1].new_line || !comments[line - 1].comment.begins_with("##")) {
  3022. break;
  3023. }
  3024. line--;
  3025. }
  3026. }
  3027. String space_prefix;
  3028. if (comments.has(line) && comments[line].comment.begins_with("##")) {
  3029. int i = 2;
  3030. for (; i < comments[line].comment.length(); i++) {
  3031. if (comments[line].comment[i] != ' ') {
  3032. break;
  3033. }
  3034. }
  3035. space_prefix = String(" ").repeat(i - 2);
  3036. }
  3037. while (comments.has(line)) {
  3038. if (!comments[line].new_line || !comments[line].comment.begins_with("##")) {
  3039. break;
  3040. }
  3041. String doc_line = comments[line++].comment.trim_prefix("##");
  3042. String title, link; // For tutorials.
  3043. if (state == DOC_LINE_NORMAL) {
  3044. // Set the read mode.
  3045. String stripped_line = doc_line.strip_edges();
  3046. if (stripped_line.is_empty()) {
  3047. if (mode == BRIEF && !p_brief.is_empty()) {
  3048. mode = DESC;
  3049. }
  3050. continue;
  3051. } else if (stripped_line.begins_with("@tutorial")) {
  3052. int begin_scan = String("@tutorial").length();
  3053. if (begin_scan >= stripped_line.length()) {
  3054. continue; // Invalid syntax.
  3055. }
  3056. if (stripped_line[begin_scan] == ':') { // No title.
  3057. // Syntax: ## @tutorial: https://godotengine.org/ // The title argument is optional.
  3058. title = "";
  3059. link = stripped_line.trim_prefix("@tutorial:").strip_edges();
  3060. } else {
  3061. /* Syntax:
  3062. * @tutorial ( The Title Here ) : https://the.url/
  3063. * ^ open ^ close ^ colon ^ url
  3064. */
  3065. int open_bracket_pos = begin_scan, close_bracket_pos = 0;
  3066. while (open_bracket_pos < stripped_line.length() && (stripped_line[open_bracket_pos] == ' ' || stripped_line[open_bracket_pos] == '\t')) {
  3067. open_bracket_pos++;
  3068. }
  3069. if (open_bracket_pos == stripped_line.length() || stripped_line[open_bracket_pos++] != '(') {
  3070. continue; // Invalid syntax.
  3071. }
  3072. close_bracket_pos = open_bracket_pos;
  3073. while (close_bracket_pos < stripped_line.length() && stripped_line[close_bracket_pos] != ')') {
  3074. close_bracket_pos++;
  3075. }
  3076. if (close_bracket_pos == stripped_line.length()) {
  3077. continue; // Invalid syntax.
  3078. }
  3079. int colon_pos = close_bracket_pos + 1;
  3080. while (colon_pos < stripped_line.length() && (stripped_line[colon_pos] == ' ' || stripped_line[colon_pos] == '\t')) {
  3081. colon_pos++;
  3082. }
  3083. if (colon_pos == stripped_line.length() || stripped_line[colon_pos++] != ':') {
  3084. continue; // Invalid syntax.
  3085. }
  3086. title = stripped_line.substr(open_bracket_pos, close_bracket_pos - open_bracket_pos).strip_edges();
  3087. link = stripped_line.substr(colon_pos).strip_edges();
  3088. }
  3089. mode = TUTORIALS;
  3090. } else if (mode == TUTORIALS) { // Tutorial docs are single line, we need a @tag after it.
  3091. mode = DONE;
  3092. }
  3093. }
  3094. switch (mode) {
  3095. case BRIEF:
  3096. p_brief += _process_doc_line(doc_line, p_brief, space_prefix, state);
  3097. break;
  3098. case DESC:
  3099. p_desc += _process_doc_line(doc_line, p_desc, space_prefix, state);
  3100. break;
  3101. case TUTORIALS:
  3102. p_tutorials.append(Pair<String, String>(title, link));
  3103. break;
  3104. case DONE:
  3105. break;
  3106. }
  3107. }
  3108. if (current_class->members.size() > 0) {
  3109. const ClassNode::Member &m = current_class->members[0];
  3110. int first_member_line = m.get_line();
  3111. if (first_member_line == line) {
  3112. p_brief = "";
  3113. p_desc = "";
  3114. p_tutorials.clear();
  3115. }
  3116. }
  3117. }
  3118. #endif // TOOLS_ENABLED
  3119. GDScriptParser::ParseRule *GDScriptParser::get_rule(GDScriptTokenizer::Token::Type p_token_type) {
  3120. // Function table for expression parsing.
  3121. // clang-format destroys the alignment here, so turn off for the table.
  3122. /* clang-format off */
  3123. static ParseRule rules[] = {
  3124. // PREFIX INFIX PRECEDENCE (for infix)
  3125. { nullptr, nullptr, PREC_NONE }, // EMPTY,
  3126. // Basic
  3127. { nullptr, nullptr, PREC_NONE }, // ANNOTATION,
  3128. { &GDScriptParser::parse_identifier, nullptr, PREC_NONE }, // IDENTIFIER,
  3129. { &GDScriptParser::parse_literal, nullptr, PREC_NONE }, // LITERAL,
  3130. // Comparison
  3131. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS,
  3132. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // LESS_EQUAL,
  3133. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER,
  3134. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // GREATER_EQUAL,
  3135. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // EQUAL_EQUAL,
  3136. { nullptr, &GDScriptParser::parse_binary_operator, PREC_COMPARISON }, // BANG_EQUAL,
  3137. // Logical
  3138. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AND,
  3139. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // OR,
  3140. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_not_in_operator, PREC_CONTENT_TEST }, // NOT,
  3141. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_AND }, // AMPERSAND_AMPERSAND,
  3142. { nullptr, &GDScriptParser::parse_binary_operator, PREC_LOGIC_OR }, // PIPE_PIPE,
  3143. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // BANG,
  3144. // Bitwise
  3145. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_AND }, // AMPERSAND,
  3146. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_OR }, // PIPE,
  3147. { &GDScriptParser::parse_unary_operator, nullptr, PREC_NONE }, // TILDE,
  3148. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_XOR }, // CARET,
  3149. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // LESS_LESS,
  3150. { nullptr, &GDScriptParser::parse_binary_operator, PREC_BIT_SHIFT }, // GREATER_GREATER,
  3151. // Math
  3152. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // PLUS,
  3153. { &GDScriptParser::parse_unary_operator, &GDScriptParser::parse_binary_operator, PREC_ADDITION_SUBTRACTION }, // MINUS,
  3154. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // STAR,
  3155. { nullptr, &GDScriptParser::parse_binary_operator, PREC_POWER }, // STAR_STAR,
  3156. { nullptr, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // SLASH,
  3157. { &GDScriptParser::parse_get_node, &GDScriptParser::parse_binary_operator, PREC_FACTOR }, // PERCENT,
  3158. // Assignment
  3159. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // EQUAL,
  3160. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PLUS_EQUAL,
  3161. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // MINUS_EQUAL,
  3162. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_EQUAL,
  3163. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // STAR_STAR_EQUAL,
  3164. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // SLASH_EQUAL,
  3165. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PERCENT_EQUAL,
  3166. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // LESS_LESS_EQUAL,
  3167. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // GREATER_GREATER_EQUAL,
  3168. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // AMPERSAND_EQUAL,
  3169. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // PIPE_EQUAL,
  3170. { nullptr, &GDScriptParser::parse_assignment, PREC_ASSIGNMENT }, // CARET_EQUAL,
  3171. // Control flow
  3172. { nullptr, &GDScriptParser::parse_ternary_operator, PREC_TERNARY }, // IF,
  3173. { nullptr, nullptr, PREC_NONE }, // ELIF,
  3174. { nullptr, nullptr, PREC_NONE }, // ELSE,
  3175. { nullptr, nullptr, PREC_NONE }, // FOR,
  3176. { nullptr, nullptr, PREC_NONE }, // WHILE,
  3177. { nullptr, nullptr, PREC_NONE }, // BREAK,
  3178. { nullptr, nullptr, PREC_NONE }, // CONTINUE,
  3179. { nullptr, nullptr, PREC_NONE }, // PASS,
  3180. { nullptr, nullptr, PREC_NONE }, // RETURN,
  3181. { nullptr, nullptr, PREC_NONE }, // MATCH,
  3182. // Keywords
  3183. { nullptr, &GDScriptParser::parse_cast, PREC_CAST }, // AS,
  3184. { nullptr, nullptr, PREC_NONE }, // ASSERT,
  3185. { &GDScriptParser::parse_await, nullptr, PREC_NONE }, // AWAIT,
  3186. { nullptr, nullptr, PREC_NONE }, // BREAKPOINT,
  3187. { nullptr, nullptr, PREC_NONE }, // CLASS,
  3188. { nullptr, nullptr, PREC_NONE }, // CLASS_NAME,
  3189. { nullptr, nullptr, PREC_NONE }, // CONST,
  3190. { nullptr, nullptr, PREC_NONE }, // ENUM,
  3191. { nullptr, nullptr, PREC_NONE }, // EXTENDS,
  3192. { &GDScriptParser::parse_lambda, nullptr, PREC_NONE }, // FUNC,
  3193. { nullptr, &GDScriptParser::parse_binary_operator, PREC_CONTENT_TEST }, // IN,
  3194. { nullptr, &GDScriptParser::parse_type_test, PREC_TYPE_TEST }, // IS,
  3195. { nullptr, nullptr, PREC_NONE }, // NAMESPACE,
  3196. { &GDScriptParser::parse_preload, nullptr, PREC_NONE }, // PRELOAD,
  3197. { &GDScriptParser::parse_self, nullptr, PREC_NONE }, // SELF,
  3198. { nullptr, nullptr, PREC_NONE }, // SIGNAL,
  3199. { nullptr, nullptr, PREC_NONE }, // STATIC,
  3200. { &GDScriptParser::parse_call, nullptr, PREC_NONE }, // SUPER,
  3201. { nullptr, nullptr, PREC_NONE }, // TRAIT,
  3202. { nullptr, nullptr, PREC_NONE }, // VAR,
  3203. { nullptr, nullptr, PREC_NONE }, // VOID,
  3204. { &GDScriptParser::parse_yield, nullptr, PREC_NONE }, // YIELD,
  3205. // Punctuation
  3206. { &GDScriptParser::parse_array, &GDScriptParser::parse_subscript, PREC_SUBSCRIPT }, // BRACKET_OPEN,
  3207. { nullptr, nullptr, PREC_NONE }, // BRACKET_CLOSE,
  3208. { &GDScriptParser::parse_dictionary, nullptr, PREC_NONE }, // BRACE_OPEN,
  3209. { nullptr, nullptr, PREC_NONE }, // BRACE_CLOSE,
  3210. { &GDScriptParser::parse_grouping, &GDScriptParser::parse_call, PREC_CALL }, // PARENTHESIS_OPEN,
  3211. { nullptr, nullptr, PREC_NONE }, // PARENTHESIS_CLOSE,
  3212. { nullptr, nullptr, PREC_NONE }, // COMMA,
  3213. { nullptr, nullptr, PREC_NONE }, // SEMICOLON,
  3214. { nullptr, &GDScriptParser::parse_attribute, PREC_ATTRIBUTE }, // PERIOD,
  3215. { nullptr, nullptr, PREC_NONE }, // PERIOD_PERIOD,
  3216. { nullptr, nullptr, PREC_NONE }, // COLON,
  3217. { &GDScriptParser::parse_get_node, nullptr, PREC_NONE }, // DOLLAR,
  3218. { nullptr, nullptr, PREC_NONE }, // FORWARD_ARROW,
  3219. { nullptr, nullptr, PREC_NONE }, // UNDERSCORE,
  3220. // Whitespace
  3221. { nullptr, nullptr, PREC_NONE }, // NEWLINE,
  3222. { nullptr, nullptr, PREC_NONE }, // INDENT,
  3223. { nullptr, nullptr, PREC_NONE }, // DEDENT,
  3224. // Constants
  3225. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_PI,
  3226. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_TAU,
  3227. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_INF,
  3228. { &GDScriptParser::parse_builtin_constant, nullptr, PREC_NONE }, // CONST_NAN,
  3229. // Error message improvement
  3230. { nullptr, nullptr, PREC_NONE }, // VCS_CONFLICT_MARKER,
  3231. { nullptr, nullptr, PREC_NONE }, // BACKTICK,
  3232. { nullptr, &GDScriptParser::parse_invalid_token, PREC_CAST }, // QUESTION_MARK,
  3233. // Special
  3234. { nullptr, nullptr, PREC_NONE }, // ERROR,
  3235. { nullptr, nullptr, PREC_NONE }, // TK_EOF,
  3236. };
  3237. /* clang-format on */
  3238. // Avoid desync.
  3239. static_assert(sizeof(rules) / sizeof(rules[0]) == GDScriptTokenizer::Token::TK_MAX, "Amount of parse rules don't match the amount of token types.");
  3240. // Let's assume this is never invalid, since nothing generates a TK_MAX.
  3241. return &rules[p_token_type];
  3242. }
  3243. bool GDScriptParser::SuiteNode::has_local(const StringName &p_name) const {
  3244. if (locals_indices.has(p_name)) {
  3245. return true;
  3246. }
  3247. if (parent_block != nullptr) {
  3248. return parent_block->has_local(p_name);
  3249. }
  3250. return false;
  3251. }
  3252. const GDScriptParser::SuiteNode::Local &GDScriptParser::SuiteNode::get_local(const StringName &p_name) const {
  3253. if (locals_indices.has(p_name)) {
  3254. return locals[locals_indices[p_name]];
  3255. }
  3256. if (parent_block != nullptr) {
  3257. return parent_block->get_local(p_name);
  3258. }
  3259. return empty;
  3260. }
  3261. bool GDScriptParser::AnnotationNode::apply(GDScriptParser *p_this, Node *p_target) {
  3262. if (is_applied) {
  3263. return true;
  3264. }
  3265. is_applied = true;
  3266. return (p_this->*(p_this->valid_annotations[name].apply))(this, p_target);
  3267. }
  3268. bool GDScriptParser::AnnotationNode::applies_to(uint32_t p_target_kinds) const {
  3269. return (info->target_kind & p_target_kinds) > 0;
  3270. }
  3271. bool GDScriptParser::validate_annotation_arguments(AnnotationNode *p_annotation) {
  3272. ERR_FAIL_COND_V_MSG(!valid_annotations.has(p_annotation->name), false, vformat(R"(Annotation "%s" not found to validate.)", p_annotation->name));
  3273. const MethodInfo &info = valid_annotations[p_annotation->name].info;
  3274. if (((info.flags & METHOD_FLAG_VARARG) == 0) && p_annotation->arguments.size() > info.arguments.size()) {
  3275. 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()));
  3276. return false;
  3277. }
  3278. if (p_annotation->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  3279. 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()));
  3280. return false;
  3281. }
  3282. // `@icon`'s argument needs to be resolved in the parser. See GH-72444.
  3283. if (p_annotation->name == SNAME("@icon")) {
  3284. ExpressionNode *argument = p_annotation->arguments[0];
  3285. if (argument->type != Node::LITERAL) {
  3286. push_error(R"(Argument 1 of annotation "@icon" must be a string literal.)", argument);
  3287. return false;
  3288. }
  3289. Variant value = static_cast<LiteralNode *>(argument)->value;
  3290. if (value.get_type() != Variant::STRING) {
  3291. push_error(R"(Argument 1 of annotation "@icon" must be a string literal.)", argument);
  3292. return false;
  3293. }
  3294. p_annotation->resolved_arguments.push_back(value);
  3295. }
  3296. // For other annotations, see `GDScriptAnalyzer::resolve_annotation()`.
  3297. return true;
  3298. }
  3299. bool GDScriptParser::tool_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  3300. #ifdef DEBUG_ENABLED
  3301. if (this->_is_tool) {
  3302. push_error(R"("@tool" annotation can only be used once.)", p_annotation);
  3303. return false;
  3304. }
  3305. #endif // DEBUG_ENABLED
  3306. this->_is_tool = true;
  3307. return true;
  3308. }
  3309. bool GDScriptParser::icon_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  3310. ERR_FAIL_COND_V_MSG(p_node->type != Node::CLASS, false, R"("@icon" annotation can only be applied to classes.)");
  3311. ERR_FAIL_COND_V(p_annotation->resolved_arguments.is_empty(), false);
  3312. ClassNode *p_class = static_cast<ClassNode *>(p_node);
  3313. #ifdef DEBUG_ENABLED
  3314. if (!p_class->icon_path.is_empty()) {
  3315. push_error(R"("@icon" annotation can only be used once.)", p_annotation);
  3316. return false;
  3317. }
  3318. if (String(p_annotation->resolved_arguments[0]).is_empty()) {
  3319. push_error(R"("@icon" annotation argument must contain the path to the icon.)", p_annotation->arguments[0]);
  3320. return false;
  3321. }
  3322. #endif // DEBUG_ENABLED
  3323. p_class->icon_path = p_annotation->resolved_arguments[0];
  3324. return true;
  3325. }
  3326. bool GDScriptParser::onready_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  3327. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, R"("@onready" annotation can only be applied to class variables.)");
  3328. if (current_class && !ClassDB::is_parent_class(current_class->get_datatype().native_type, SNAME("Node"))) {
  3329. push_error(R"("@onready" can only be used in classes that inherit "Node".)", p_annotation);
  3330. }
  3331. VariableNode *variable = static_cast<VariableNode *>(p_node);
  3332. if (variable->onready) {
  3333. push_error(R"("@onready" annotation can only be used once per variable.)");
  3334. return false;
  3335. }
  3336. variable->onready = true;
  3337. current_class->onready_used = true;
  3338. return true;
  3339. }
  3340. template <PropertyHint t_hint, Variant::Type t_type>
  3341. bool GDScriptParser::export_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  3342. ERR_FAIL_COND_V_MSG(p_node->type != Node::VARIABLE, false, vformat(R"("%s" annotation can only be applied to variables.)", p_annotation->name));
  3343. VariableNode *variable = static_cast<VariableNode *>(p_node);
  3344. if (variable->exported) {
  3345. push_error(vformat(R"(Annotation "%s" cannot be used with another "@export" annotation.)", p_annotation->name), p_annotation);
  3346. return false;
  3347. }
  3348. variable->exported = true;
  3349. variable->export_info.type = t_type;
  3350. variable->export_info.hint = t_hint;
  3351. String hint_string;
  3352. for (int i = 0; i < p_annotation->resolved_arguments.size(); i++) {
  3353. String arg_string = String(p_annotation->resolved_arguments[i]);
  3354. if (p_annotation->name != SNAME("@export_placeholder")) {
  3355. if (arg_string.is_empty()) {
  3356. push_error(vformat(R"(Argument %d of annotation "%s" is empty.)", i + 1, p_annotation->name), p_annotation->arguments[i]);
  3357. return false;
  3358. }
  3359. if (arg_string.contains(",")) {
  3360. 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]);
  3361. return false;
  3362. }
  3363. }
  3364. if (p_annotation->name == SNAME("@export_flags")) {
  3365. const int64_t max_flags = 32;
  3366. Vector<String> t = arg_string.split(":", true, 1);
  3367. if (t[0].is_empty()) {
  3368. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag name.)", i + 1), p_annotation->arguments[i]);
  3369. return false;
  3370. }
  3371. if (t.size() == 2) {
  3372. if (t[1].is_empty()) {
  3373. push_error(vformat(R"(Invalid argument %d of annotation "@export_flags": Expected flag value.)", i + 1), p_annotation->arguments[i]);
  3374. return false;
  3375. }
  3376. if (!t[1].is_valid_int()) {
  3377. 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]);
  3378. return false;
  3379. }
  3380. int64_t value = t[1].to_int();
  3381. if (value < 1 || value >= (1LL << max_flags)) {
  3382. 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]);
  3383. return false;
  3384. }
  3385. } else if (i >= max_flags) {
  3386. 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]);
  3387. return false;
  3388. }
  3389. }
  3390. if (i > 0) {
  3391. hint_string += ",";
  3392. }
  3393. hint_string += arg_string;
  3394. }
  3395. variable->export_info.hint_string = hint_string;
  3396. // This is called after the analyzer is done finding the type, so this should be set here.
  3397. DataType export_type = variable->get_datatype();
  3398. if (p_annotation->name == SNAME("@export_range")) {
  3399. if (export_type.builtin_type == Variant::INT) {
  3400. variable->export_info.type = Variant::INT;
  3401. }
  3402. }
  3403. if (p_annotation->name == SNAME("@export_multiline")) {
  3404. if (export_type.builtin_type == Variant::ARRAY && export_type.has_container_element_type()) {
  3405. DataType inner_type = export_type.get_container_element_type();
  3406. if (inner_type.builtin_type != Variant::STRING) {
  3407. 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);
  3408. return false;
  3409. }
  3410. String hint_prefix = itos(inner_type.builtin_type) + "/" + itos(variable->export_info.hint);
  3411. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  3412. variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
  3413. variable->export_info.type = Variant::ARRAY;
  3414. return true;
  3415. } else if (export_type.builtin_type == Variant::DICTIONARY) {
  3416. variable->export_info.type = Variant::DICTIONARY;
  3417. return true;
  3418. } else if (export_type.builtin_type == Variant::PACKED_STRING_ARRAY) {
  3419. String hint_prefix = itos(Variant::STRING) + "/" + itos(variable->export_info.hint);
  3420. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  3421. variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
  3422. variable->export_info.type = Variant::PACKED_STRING_ARRAY;
  3423. return true;
  3424. }
  3425. }
  3426. if (p_annotation->name == SNAME("@export")) {
  3427. if (variable->datatype_specifier == nullptr && variable->initializer == nullptr) {
  3428. push_error(R"(Cannot use simple "@export" annotation with variable without type or initializer, since type can't be inferred.)", p_annotation);
  3429. return false;
  3430. }
  3431. bool is_array = false;
  3432. if (export_type.builtin_type == Variant::ARRAY && export_type.has_container_element_type()) {
  3433. export_type = export_type.get_container_element_type(); // Use inner type for.
  3434. is_array = true;
  3435. }
  3436. if (export_type.is_variant() || export_type.has_no_type()) {
  3437. push_error(R"(Cannot use simple "@export" annotation because the type of the initialized value can't be inferred.)", p_annotation);
  3438. return false;
  3439. }
  3440. switch (export_type.kind) {
  3441. case GDScriptParser::DataType::BUILTIN:
  3442. variable->export_info.type = export_type.builtin_type;
  3443. variable->export_info.hint = PROPERTY_HINT_NONE;
  3444. variable->export_info.hint_string = Variant::get_type_name(export_type.builtin_type);
  3445. break;
  3446. case GDScriptParser::DataType::NATIVE:
  3447. if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
  3448. variable->export_info.type = Variant::OBJECT;
  3449. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  3450. variable->export_info.hint_string = export_type.native_type;
  3451. } else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
  3452. variable->export_info.type = Variant::OBJECT;
  3453. variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
  3454. variable->export_info.hint_string = export_type.native_type;
  3455. } else {
  3456. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", variable);
  3457. return false;
  3458. }
  3459. break;
  3460. case GDScriptParser::DataType::CLASS:
  3461. if (ClassDB::is_parent_class(export_type.native_type, SNAME("Resource"))) {
  3462. variable->export_info.type = Variant::OBJECT;
  3463. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  3464. variable->export_info.hint_string = export_type.to_string();
  3465. } else if (ClassDB::is_parent_class(export_type.native_type, SNAME("Node"))) {
  3466. variable->export_info.type = Variant::OBJECT;
  3467. variable->export_info.hint = PROPERTY_HINT_NODE_TYPE;
  3468. variable->export_info.hint_string = export_type.to_string();
  3469. } else {
  3470. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", variable);
  3471. return false;
  3472. }
  3473. break;
  3474. case GDScriptParser::DataType::SCRIPT: {
  3475. StringName class_name;
  3476. StringName native_base;
  3477. if (export_type.script_type.is_valid()) {
  3478. class_name = export_type.script_type->get_language()->get_global_class_name(export_type.script_type->get_path());
  3479. native_base = export_type.script_type->get_instance_base_type();
  3480. }
  3481. if (class_name == StringName()) {
  3482. Ref<Script> script = ResourceLoader::load(export_type.script_path, SNAME("Script"));
  3483. if (script.is_valid()) {
  3484. class_name = script->get_language()->get_global_class_name(export_type.script_path);
  3485. native_base = script->get_instance_base_type();
  3486. }
  3487. }
  3488. if (class_name != StringName() && native_base != StringName() && ClassDB::is_parent_class(native_base, SNAME("Resource"))) {
  3489. variable->export_info.type = Variant::OBJECT;
  3490. variable->export_info.hint = PROPERTY_HINT_RESOURCE_TYPE;
  3491. variable->export_info.hint_string = class_name;
  3492. }
  3493. } break;
  3494. case GDScriptParser::DataType::ENUM: {
  3495. variable->export_info.type = Variant::INT;
  3496. variable->export_info.hint = PROPERTY_HINT_ENUM;
  3497. String enum_hint_string;
  3498. bool first = true;
  3499. for (const KeyValue<StringName, int64_t> &E : export_type.enum_values) {
  3500. if (!first) {
  3501. enum_hint_string += ",";
  3502. } else {
  3503. first = false;
  3504. }
  3505. enum_hint_string += E.key.operator String().capitalize().xml_escape();
  3506. enum_hint_string += ":";
  3507. enum_hint_string += String::num_int64(E.value).xml_escape();
  3508. }
  3509. variable->export_info.hint_string = enum_hint_string;
  3510. } break;
  3511. default:
  3512. push_error(R"(Export type can only be built-in, a resource, a node, or an enum.)", variable);
  3513. break;
  3514. }
  3515. if (is_array) {
  3516. String hint_prefix = itos(variable->export_info.type);
  3517. if (variable->export_info.hint) {
  3518. hint_prefix += "/" + itos(variable->export_info.hint);
  3519. }
  3520. variable->export_info.hint = PROPERTY_HINT_TYPE_STRING;
  3521. variable->export_info.hint_string = hint_prefix + ":" + variable->export_info.hint_string;
  3522. variable->export_info.type = Variant::ARRAY;
  3523. }
  3524. } else if (p_annotation->name == SNAME("@export_enum")) {
  3525. Variant::Type enum_type = Variant::INT;
  3526. if (export_type.kind == DataType::BUILTIN && export_type.builtin_type == Variant::STRING) {
  3527. enum_type = Variant::STRING;
  3528. } else if (export_type.is_variant() && variable->initializer != nullptr) {
  3529. DataType initializer_type = variable->initializer->get_datatype();
  3530. if (initializer_type.kind == DataType::BUILTIN && initializer_type.builtin_type == Variant::STRING) {
  3531. enum_type = Variant::STRING;
  3532. }
  3533. }
  3534. variable->export_info.type = enum_type;
  3535. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != enum_type)) {
  3536. 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);
  3537. return false;
  3538. }
  3539. } else {
  3540. // Validate variable type with export.
  3541. if (!export_type.is_variant() && (export_type.kind != DataType::BUILTIN || export_type.builtin_type != t_type)) {
  3542. // Allow float/int conversion.
  3543. if ((t_type != Variant::FLOAT || export_type.builtin_type != Variant::INT) && (t_type != Variant::INT || export_type.builtin_type != Variant::FLOAT)) {
  3544. 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);
  3545. return false;
  3546. }
  3547. }
  3548. }
  3549. return true;
  3550. }
  3551. template <PropertyUsageFlags t_usage>
  3552. bool GDScriptParser::export_group_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  3553. AnnotationNode *annotation = const_cast<AnnotationNode *>(p_annotation);
  3554. if (annotation->resolved_arguments.is_empty()) {
  3555. return false;
  3556. }
  3557. annotation->export_info.name = annotation->resolved_arguments[0];
  3558. switch (t_usage) {
  3559. case PROPERTY_USAGE_CATEGORY: {
  3560. annotation->export_info.usage = t_usage;
  3561. } break;
  3562. case PROPERTY_USAGE_GROUP: {
  3563. annotation->export_info.usage = t_usage;
  3564. if (annotation->resolved_arguments.size() == 2) {
  3565. annotation->export_info.hint_string = annotation->resolved_arguments[1];
  3566. }
  3567. } break;
  3568. case PROPERTY_USAGE_SUBGROUP: {
  3569. annotation->export_info.usage = t_usage;
  3570. if (annotation->resolved_arguments.size() == 2) {
  3571. annotation->export_info.hint_string = annotation->resolved_arguments[1];
  3572. }
  3573. } break;
  3574. }
  3575. return true;
  3576. }
  3577. bool GDScriptParser::warning_annotations(const AnnotationNode *p_annotation, Node *p_node) {
  3578. #ifdef DEBUG_ENABLED
  3579. bool has_error = false;
  3580. for (const Variant &warning_name : p_annotation->resolved_arguments) {
  3581. GDScriptWarning::Code warning = GDScriptWarning::get_code_from_name(String(warning_name).to_upper());
  3582. if (warning == GDScriptWarning::WARNING_MAX) {
  3583. push_error(vformat(R"(Invalid warning name: "%s".)", warning_name), p_annotation);
  3584. has_error = true;
  3585. } else {
  3586. p_node->ignored_warnings.push_back(warning);
  3587. }
  3588. }
  3589. return !has_error;
  3590. #else // ! DEBUG_ENABLED
  3591. // Only available in debug builds.
  3592. return true;
  3593. #endif // DEBUG_ENABLED
  3594. }
  3595. bool GDScriptParser::rpc_annotation(const AnnotationNode *p_annotation, Node *p_node) {
  3596. ERR_FAIL_COND_V_MSG(p_node->type != Node::FUNCTION, false, vformat(R"("%s" annotation can only be applied to functions.)", p_annotation->name));
  3597. FunctionNode *function = static_cast<FunctionNode *>(p_node);
  3598. if (function->rpc_config.get_type() != Variant::NIL) {
  3599. push_error(R"(RPC annotations can only be used once per function.)", p_annotation);
  3600. return false;
  3601. }
  3602. Dictionary rpc_config;
  3603. rpc_config["rpc_mode"] = MultiplayerAPI::RPC_MODE_AUTHORITY;
  3604. if (!p_annotation->resolved_arguments.is_empty()) {
  3605. int last = p_annotation->resolved_arguments.size() - 1;
  3606. if (p_annotation->resolved_arguments[last].get_type() == Variant::INT) {
  3607. rpc_config["channel"] = p_annotation->resolved_arguments[last].operator int();
  3608. last -= 1;
  3609. }
  3610. if (last > 3) {
  3611. push_error(R"(Invalid RPC arguments. At most 4 arguments are allowed, where only the last argument can be an integer to specify the channel.')", p_annotation);
  3612. return false;
  3613. }
  3614. unsigned char locality_args = 0;
  3615. unsigned char permission_args = 0;
  3616. unsigned char transfer_mode_args = 0;
  3617. for (int i = last; i >= 0; i--) {
  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