gdscript_parser.cpp 170 KB

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