gdscript_parser.cpp 166 KB

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