gdscript_parser.cpp 170 KB

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