gdscript_parser.cpp 166 KB

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