gdscript_analyzer.cpp 147 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819
  1. /*************************************************************************/
  2. /* gdscript_analyzer.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "gdscript_analyzer.h"
  31. #include "core/config/engine.h"
  32. #include "core/config/project_settings.h"
  33. #include "core/io/file_access.h"
  34. #include "core/io/resource_loader.h"
  35. #include "core/object/class_db.h"
  36. #include "core/object/script_language.h"
  37. #include "core/templates/hash_map.h"
  38. #include "gdscript.h"
  39. #include "gdscript_utility_functions.h"
  40. static MethodInfo info_from_utility_func(const StringName &p_function) {
  41. ERR_FAIL_COND_V(!Variant::has_utility_function(p_function), MethodInfo());
  42. MethodInfo info(p_function);
  43. if (Variant::has_utility_function_return_value(p_function)) {
  44. info.return_val.type = Variant::get_utility_function_return_type(p_function);
  45. if (info.return_val.type == Variant::NIL) {
  46. info.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  47. }
  48. }
  49. if (Variant::is_utility_function_vararg(p_function)) {
  50. info.flags |= METHOD_FLAG_VARARG;
  51. } else {
  52. for (int i = 0; i < Variant::get_utility_function_argument_count(p_function); i++) {
  53. PropertyInfo pi;
  54. #ifdef DEBUG_METHODS_ENABLED
  55. pi.name = Variant::get_utility_function_argument_name(p_function, i);
  56. #else
  57. pi.name = "arg" + itos(i + 1);
  58. #endif
  59. pi.type = Variant::get_utility_function_argument_type(p_function, i);
  60. if (pi.type == Variant::NIL) {
  61. pi.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
  62. }
  63. info.arguments.push_back(pi);
  64. }
  65. }
  66. return info;
  67. }
  68. static GDScriptParser::DataType make_callable_type(const MethodInfo &p_info) {
  69. GDScriptParser::DataType type;
  70. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  71. type.kind = GDScriptParser::DataType::BUILTIN;
  72. type.builtin_type = Variant::CALLABLE;
  73. type.is_constant = true;
  74. type.method_info = p_info;
  75. return type;
  76. }
  77. static GDScriptParser::DataType make_signal_type(const MethodInfo &p_info) {
  78. GDScriptParser::DataType type;
  79. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  80. type.kind = GDScriptParser::DataType::BUILTIN;
  81. type.builtin_type = Variant::SIGNAL;
  82. type.is_constant = true;
  83. type.method_info = p_info;
  84. return type;
  85. }
  86. static GDScriptParser::DataType make_native_meta_type(const StringName &p_class_name) {
  87. GDScriptParser::DataType type;
  88. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  89. type.kind = GDScriptParser::DataType::NATIVE;
  90. type.builtin_type = Variant::OBJECT;
  91. type.is_constant = true;
  92. type.native_type = p_class_name;
  93. type.is_meta_type = true;
  94. return type;
  95. }
  96. static GDScriptParser::DataType make_native_enum_type(const StringName &p_native_class, const StringName &p_enum_name) {
  97. GDScriptParser::DataType type;
  98. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  99. type.kind = GDScriptParser::DataType::ENUM;
  100. type.builtin_type = Variant::OBJECT;
  101. type.is_constant = true;
  102. type.is_meta_type = true;
  103. List<StringName> enum_values;
  104. ClassDB::get_enum_constants(p_native_class, p_enum_name, &enum_values);
  105. for (const StringName &E : enum_values) {
  106. type.enum_values[E] = ClassDB::get_integer_constant(p_native_class, E);
  107. }
  108. return type;
  109. }
  110. static GDScriptParser::DataType make_builtin_meta_type(Variant::Type p_type) {
  111. GDScriptParser::DataType type;
  112. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  113. type.kind = GDScriptParser::DataType::BUILTIN;
  114. type.builtin_type = p_type;
  115. type.is_constant = true;
  116. type.is_meta_type = true;
  117. return type;
  118. }
  119. bool GDScriptAnalyzer::has_member_name_conflict_in_script_class(const StringName &p_member_name, const GDScriptParser::ClassNode *p_class) {
  120. if (p_class->members_indices.has(p_member_name)) {
  121. int index = p_class->members_indices[p_member_name];
  122. const GDScriptParser::ClassNode::Member *member = &p_class->members[index];
  123. if (member->type == GDScriptParser::ClassNode::Member::VARIABLE ||
  124. member->type == GDScriptParser::ClassNode::Member::CONSTANT ||
  125. member->type == GDScriptParser::ClassNode::Member::ENUM ||
  126. member->type == GDScriptParser::ClassNode::Member::ENUM_VALUE ||
  127. member->type == GDScriptParser::ClassNode::Member::CLASS ||
  128. member->type == GDScriptParser::ClassNode::Member::SIGNAL) {
  129. return true;
  130. }
  131. }
  132. return false;
  133. }
  134. bool GDScriptAnalyzer::has_member_name_conflict_in_native_type(const StringName &p_member_name, const StringName &p_native_type_string) {
  135. if (ClassDB::has_signal(p_native_type_string, p_member_name)) {
  136. return true;
  137. }
  138. if (ClassDB::has_property(p_native_type_string, p_member_name)) {
  139. return true;
  140. }
  141. if (ClassDB::has_integer_constant(p_native_type_string, p_member_name)) {
  142. return true;
  143. }
  144. return false;
  145. }
  146. Error GDScriptAnalyzer::check_native_member_name_conflict(const StringName &p_member_name, const GDScriptParser::Node *p_member_node, const StringName &p_native_type_string) {
  147. if (has_member_name_conflict_in_native_type(p_member_name, p_native_type_string)) {
  148. push_error(vformat(R"(Member "%s" redefined (original in native class '%s'))", p_member_name, p_native_type_string), p_member_node);
  149. return ERR_PARSE_ERROR;
  150. }
  151. if (class_exists(p_member_name)) {
  152. push_error(vformat(R"(The member "%s" shadows a native class.)", p_member_name), p_member_node);
  153. return ERR_PARSE_ERROR;
  154. }
  155. return OK;
  156. }
  157. Error GDScriptAnalyzer::check_class_member_name_conflict(const GDScriptParser::ClassNode *p_class_node, const StringName &p_member_name, const GDScriptParser::Node *p_member_node) {
  158. const GDScriptParser::DataType *current_data_type = &p_class_node->base_type;
  159. while (current_data_type && current_data_type->kind == GDScriptParser::DataType::Kind::CLASS) {
  160. GDScriptParser::ClassNode *current_class_node = current_data_type->class_type;
  161. if (has_member_name_conflict_in_script_class(p_member_name, current_class_node)) {
  162. push_error(vformat(R"(The member "%s" already exists in a parent class.)", p_member_name),
  163. p_member_node);
  164. return ERR_PARSE_ERROR;
  165. }
  166. current_data_type = &current_class_node->base_type;
  167. }
  168. if (current_data_type && current_data_type->kind == GDScriptParser::DataType::Kind::NATIVE) {
  169. if (current_data_type->native_type != StringName("")) {
  170. return check_native_member_name_conflict(
  171. p_member_name,
  172. p_member_node,
  173. current_data_type->native_type);
  174. }
  175. }
  176. return OK;
  177. }
  178. Error GDScriptAnalyzer::resolve_inheritance(GDScriptParser::ClassNode *p_class, bool p_recursive) {
  179. if (p_class->base_type.is_set()) {
  180. // Already resolved
  181. return OK;
  182. }
  183. if (p_class == parser->head) {
  184. if (p_class->identifier) {
  185. p_class->fqcn = p_class->identifier->name;
  186. } else {
  187. p_class->fqcn = parser->script_path;
  188. }
  189. } else {
  190. p_class->fqcn = p_class->outer->fqcn + "::" + String(p_class->identifier->name);
  191. }
  192. if (p_class->identifier) {
  193. StringName class_name = p_class->identifier->name;
  194. if (class_exists(class_name)) {
  195. push_error(vformat(R"(Class "%s" hides a native class.)", class_name), p_class->identifier);
  196. } else if (ScriptServer::is_global_class(class_name) && (ScriptServer::get_global_class_path(class_name) != parser->script_path || p_class != parser->head)) {
  197. push_error(vformat(R"(Class "%s" hides a global script class.)", class_name), p_class->identifier);
  198. } else if (ProjectSettings::get_singleton()->has_autoload(class_name) && ProjectSettings::get_singleton()->get_autoload(class_name).is_singleton) {
  199. push_error(vformat(R"(Class "%s" hides an autoload singleton.)", class_name), p_class->identifier);
  200. }
  201. }
  202. GDScriptParser::DataType result;
  203. // Set datatype for class.
  204. GDScriptParser::DataType class_type;
  205. class_type.is_constant = true;
  206. class_type.is_meta_type = true;
  207. class_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  208. class_type.kind = GDScriptParser::DataType::CLASS;
  209. class_type.class_type = p_class;
  210. class_type.script_path = parser->script_path;
  211. p_class->set_datatype(class_type);
  212. if (!p_class->extends_used) {
  213. result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  214. result.kind = GDScriptParser::DataType::NATIVE;
  215. result.native_type = "RefCounted";
  216. } else {
  217. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  218. GDScriptParser::DataType base;
  219. int extends_index = 0;
  220. if (!p_class->extends_path.is_empty()) {
  221. Ref<GDScriptParserRef> parser = get_parser_for(p_class->extends_path);
  222. if (parser.is_null()) {
  223. push_error(vformat(R"(Could not resolve super class path "%s".)", p_class->extends_path), p_class);
  224. return ERR_PARSE_ERROR;
  225. }
  226. Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
  227. if (err != OK) {
  228. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", p_class->extends_path), p_class);
  229. return err;
  230. }
  231. base = parser->get_parser()->head->get_datatype();
  232. } else {
  233. if (p_class->extends.is_empty()) {
  234. return ERR_PARSE_ERROR;
  235. }
  236. const StringName &name = p_class->extends[extends_index++];
  237. base.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  238. if (ScriptServer::is_global_class(name)) {
  239. String base_path = ScriptServer::get_global_class_path(name);
  240. if (base_path == parser->script_path) {
  241. base = parser->head->get_datatype();
  242. } else {
  243. Ref<GDScriptParserRef> parser = get_parser_for(base_path);
  244. if (parser.is_null()) {
  245. push_error(vformat(R"(Could not resolve super class "%s".)", name), p_class);
  246. return ERR_PARSE_ERROR;
  247. }
  248. Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
  249. if (err != OK) {
  250. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
  251. return err;
  252. }
  253. base = parser->get_parser()->head->get_datatype();
  254. }
  255. } else if (ProjectSettings::get_singleton()->has_autoload(name) && ProjectSettings::get_singleton()->get_autoload(name).is_singleton) {
  256. const ProjectSettings::AutoloadInfo &info = ProjectSettings::get_singleton()->get_autoload(name);
  257. if (info.path.get_extension().to_lower() != ".gd") {
  258. push_error(vformat(R"(Singleton %s is not a GDScript.)", info.name), p_class);
  259. return ERR_PARSE_ERROR;
  260. }
  261. Ref<GDScriptParserRef> parser = get_parser_for(info.path);
  262. if (parser.is_null()) {
  263. push_error(vformat(R"(Could not parse singleton from "%s".)", info.path), p_class);
  264. return ERR_PARSE_ERROR;
  265. }
  266. Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
  267. if (err != OK) {
  268. push_error(vformat(R"(Could not resolve super class inheritance from "%s".)", name), p_class);
  269. return err;
  270. }
  271. } else if (class_exists(name) && ClassDB::can_instantiate(name)) {
  272. base.kind = GDScriptParser::DataType::NATIVE;
  273. base.native_type = name;
  274. } else {
  275. // Look for other classes in script.
  276. GDScriptParser::ClassNode *look_class = p_class;
  277. bool found = false;
  278. while (look_class != nullptr) {
  279. if (look_class->identifier && look_class->identifier->name == name) {
  280. if (!look_class->get_datatype().is_set()) {
  281. Error err = resolve_inheritance(look_class, false);
  282. if (err) {
  283. return err;
  284. }
  285. }
  286. base = look_class->get_datatype();
  287. found = true;
  288. break;
  289. }
  290. if (look_class->members_indices.has(name) && look_class->get_member(name).type == GDScriptParser::ClassNode::Member::CLASS) {
  291. GDScriptParser::ClassNode::Member member = look_class->get_member(name);
  292. if (!member.m_class->get_datatype().is_set()) {
  293. Error err = resolve_inheritance(member.m_class, false);
  294. if (err) {
  295. return err;
  296. }
  297. }
  298. base = member.m_class->get_datatype();
  299. found = true;
  300. break;
  301. }
  302. look_class = look_class->outer;
  303. }
  304. if (!found) {
  305. push_error(vformat(R"(Could not find base class "%s".)", name), p_class);
  306. return ERR_PARSE_ERROR;
  307. }
  308. }
  309. }
  310. for (int index = extends_index; index < p_class->extends.size(); index++) {
  311. if (base.kind != GDScriptParser::DataType::CLASS) {
  312. push_error(R"(Super type "%s" is not a GDScript. Cannot get nested types.)", p_class);
  313. return ERR_PARSE_ERROR;
  314. }
  315. // TODO: Extends could use identifier nodes. That way errors can be pointed out properly and it can be used here.
  316. GDScriptParser::IdentifierNode *id = parser->alloc_node<GDScriptParser::IdentifierNode>();
  317. id->name = p_class->extends[index];
  318. reduce_identifier_from_base(id, &base);
  319. GDScriptParser::DataType id_type = id->get_datatype();
  320. if (!id_type.is_set()) {
  321. push_error(vformat(R"(Could not find type "%s" under base "%s".)", id->name, base.to_string()), p_class);
  322. }
  323. base = id_type;
  324. }
  325. result = base;
  326. }
  327. if (!result.is_set()) {
  328. // TODO: More specific error messages.
  329. push_error(vformat(R"(Could not resolve inheritance for class "%s".)", p_class->identifier == nullptr ? "<main>" : p_class->identifier->name), p_class);
  330. return ERR_PARSE_ERROR;
  331. }
  332. // Check for cyclic inheritance.
  333. const GDScriptParser::ClassNode *base_class = result.class_type;
  334. while (base_class) {
  335. if (base_class->fqcn == p_class->fqcn) {
  336. push_error("Cyclic inheritance.", p_class);
  337. return ERR_PARSE_ERROR;
  338. }
  339. base_class = base_class->base_type.class_type;
  340. }
  341. p_class->base_type = result;
  342. class_type.native_type = result.native_type;
  343. p_class->set_datatype(class_type);
  344. if (p_recursive) {
  345. for (int i = 0; i < p_class->members.size(); i++) {
  346. if (p_class->members[i].type == GDScriptParser::ClassNode::Member::CLASS) {
  347. Error err = resolve_inheritance(p_class->members[i].m_class, true);
  348. if (err) {
  349. return err;
  350. }
  351. }
  352. }
  353. }
  354. return OK;
  355. }
  356. GDScriptParser::DataType GDScriptAnalyzer::resolve_datatype(GDScriptParser::TypeNode *p_type) {
  357. GDScriptParser::DataType result;
  358. if (p_type == nullptr) {
  359. result.kind = GDScriptParser::DataType::VARIANT;
  360. return result;
  361. }
  362. result.type_source = result.ANNOTATED_EXPLICIT;
  363. result.builtin_type = Variant::OBJECT;
  364. if (p_type->type_chain.is_empty()) {
  365. // void.
  366. result.kind = GDScriptParser::DataType::BUILTIN;
  367. result.builtin_type = Variant::NIL;
  368. p_type->set_datatype(result);
  369. return result;
  370. }
  371. StringName first = p_type->type_chain[0]->name;
  372. if (first == "Variant") {
  373. result.kind = GDScriptParser::DataType::VARIANT;
  374. if (p_type->type_chain.size() > 1) {
  375. push_error(R"("Variant" type don't contain nested types.)", p_type->type_chain[1]);
  376. return GDScriptParser::DataType();
  377. }
  378. return result;
  379. }
  380. if (first == "Object") {
  381. result.kind = GDScriptParser::DataType::NATIVE;
  382. result.native_type = "Object";
  383. if (p_type->type_chain.size() > 1) {
  384. push_error(R"("Object" type don't contain nested types.)", p_type->type_chain[1]);
  385. return GDScriptParser::DataType();
  386. }
  387. return result;
  388. }
  389. if (GDScriptParser::get_builtin_type(first) < Variant::VARIANT_MAX) {
  390. // Built-in types.
  391. if (p_type->type_chain.size() > 1) {
  392. push_error(R"(Built-in types don't contain nested types.)", p_type->type_chain[1]);
  393. return GDScriptParser::DataType();
  394. }
  395. result.kind = GDScriptParser::DataType::BUILTIN;
  396. result.builtin_type = GDScriptParser::get_builtin_type(first);
  397. if (result.builtin_type == Variant::ARRAY) {
  398. GDScriptParser::DataType container_type = resolve_datatype(p_type->container_type);
  399. if (container_type.kind != GDScriptParser::DataType::VARIANT) {
  400. result.set_container_element_type(container_type);
  401. }
  402. }
  403. } else if (class_exists(first)) {
  404. // Native engine classes.
  405. result.kind = GDScriptParser::DataType::NATIVE;
  406. result.native_type = first;
  407. } else if (ScriptServer::is_global_class(first)) {
  408. if (parser->script_path == ScriptServer::get_global_class_path(first)) {
  409. result = parser->head->get_datatype();
  410. } else {
  411. Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(first));
  412. if (ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) {
  413. push_error(vformat(R"(Could not parse global class "%s" from "%s".)", first, ScriptServer::get_global_class_path(first)), p_type);
  414. return GDScriptParser::DataType();
  415. }
  416. result = ref->get_parser()->head->get_datatype();
  417. }
  418. } else if (ProjectSettings::get_singleton()->has_autoload(first) && ProjectSettings::get_singleton()->get_autoload(first).is_singleton) {
  419. const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(first);
  420. Ref<GDScriptParserRef> ref = get_parser_for(autoload.path);
  421. if (ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) {
  422. push_error(vformat(R"(Could not parse singleton "%s" from "%s".)", first, autoload.path), p_type);
  423. return GDScriptParser::DataType();
  424. }
  425. result = ref->get_parser()->head->get_datatype();
  426. } else if (ClassDB::has_enum(parser->current_class->base_type.native_type, first)) {
  427. // Native enum in current class.
  428. result = make_native_enum_type(parser->current_class->base_type.native_type, first);
  429. } else {
  430. // Classes in current scope.
  431. GDScriptParser::ClassNode *script_class = parser->current_class;
  432. bool found = false;
  433. while (!found && script_class != nullptr) {
  434. if (script_class->identifier && script_class->identifier->name == first) {
  435. result = script_class->get_datatype();
  436. found = true;
  437. break;
  438. }
  439. if (script_class->members_indices.has(first)) {
  440. GDScriptParser::ClassNode::Member member = script_class->members[script_class->members_indices[first]];
  441. switch (member.type) {
  442. case GDScriptParser::ClassNode::Member::CLASS:
  443. result = member.m_class->get_datatype();
  444. found = true;
  445. break;
  446. case GDScriptParser::ClassNode::Member::ENUM:
  447. result = member.m_enum->get_datatype();
  448. found = true;
  449. break;
  450. case GDScriptParser::ClassNode::Member::CONSTANT:
  451. if (member.constant->get_datatype().is_meta_type) {
  452. result = member.constant->get_datatype();
  453. result.is_meta_type = false;
  454. found = true;
  455. break;
  456. } else if (Ref<Script>(member.constant->initializer->reduced_value).is_valid()) {
  457. Ref<GDScript> gdscript = member.constant->initializer->reduced_value;
  458. if (gdscript.is_valid()) {
  459. Ref<GDScriptParserRef> ref = get_parser_for(gdscript->get_path());
  460. if (ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED) != OK) {
  461. push_error(vformat(R"(Could not parse script from "%s".)", gdscript->get_path()), p_type);
  462. return GDScriptParser::DataType();
  463. }
  464. result = ref->get_parser()->head->get_datatype();
  465. result.is_meta_type = false;
  466. } else {
  467. Ref<GDScript> script = member.constant->initializer->reduced_value;
  468. result.kind = GDScriptParser::DataType::SCRIPT;
  469. result.builtin_type = Variant::OBJECT;
  470. result.script_type = script;
  471. result.script_path = script->get_path();
  472. result.native_type = script->get_instance_base_type();
  473. }
  474. break;
  475. }
  476. [[fallthrough]];
  477. default:
  478. push_error(vformat(R"("%s" is a %s but does not contain a type.)", first, member.get_type_name()), p_type);
  479. return GDScriptParser::DataType();
  480. }
  481. }
  482. script_class = script_class->outer;
  483. }
  484. }
  485. if (!result.is_set()) {
  486. push_error(vformat(R"("%s" was not found in the current scope.)", first), p_type);
  487. result.kind = GDScriptParser::DataType::VARIANT; // Leave Variant anyway so future type check don't use an unresolved type.
  488. return result;
  489. }
  490. if (p_type->type_chain.size() > 1) {
  491. if (result.kind == GDScriptParser::DataType::CLASS) {
  492. for (int i = 1; i < p_type->type_chain.size(); i++) {
  493. GDScriptParser::DataType base = result;
  494. reduce_identifier_from_base(p_type->type_chain[i], &base);
  495. result = p_type->type_chain[i]->get_datatype();
  496. if (!result.is_set()) {
  497. push_error(vformat(R"(Could not find type "%s" under base "%s".)", p_type->type_chain[i]->name, base.to_string()), p_type->type_chain[1]);
  498. result.kind = GDScriptParser::DataType::VARIANT; // Leave Variant anyway so future type check don't use an unresolved type.
  499. return result;
  500. } else if (!result.is_meta_type) {
  501. push_error(vformat(R"(Member "%s" under base "%s" is not a valid type.)", p_type->type_chain[i]->name, base.to_string()), p_type->type_chain[1]);
  502. result.kind = GDScriptParser::DataType::VARIANT; // Leave Variant anyway so future type check don't use an unresolved type.
  503. return result;
  504. }
  505. }
  506. } else if (result.kind == GDScriptParser::DataType::NATIVE) {
  507. // Only enums allowed for native.
  508. if (ClassDB::has_enum(result.native_type, p_type->type_chain[1]->name)) {
  509. if (p_type->type_chain.size() > 2) {
  510. push_error(R"(Enums cannot contain nested types.)", p_type->type_chain[2]);
  511. } else {
  512. result = make_native_enum_type(result.native_type, p_type->type_chain[1]->name);
  513. }
  514. }
  515. } else {
  516. push_error(vformat(R"(Could not find nested type "%s" under base "%s".)", p_type->type_chain[1]->name, result.to_string()), p_type->type_chain[1]);
  517. result.kind = GDScriptParser::DataType::VARIANT; // Leave Variant anyway so future type check don't use an unresolved type.
  518. return result;
  519. }
  520. }
  521. if (result.builtin_type != Variant::ARRAY && p_type->container_type != nullptr) {
  522. push_error("Only arrays can specify the collection element type.", p_type);
  523. }
  524. p_type->set_datatype(result);
  525. return result;
  526. }
  527. void GDScriptAnalyzer::resolve_class_interface(GDScriptParser::ClassNode *p_class) {
  528. if (p_class->resolved_interface) {
  529. return;
  530. }
  531. p_class->resolved_interface = true;
  532. GDScriptParser::ClassNode *previous_class = parser->current_class;
  533. parser->current_class = p_class;
  534. for (int i = 0; i < p_class->members.size(); i++) {
  535. GDScriptParser::ClassNode::Member member = p_class->members[i];
  536. switch (member.type) {
  537. case GDScriptParser::ClassNode::Member::VARIABLE: {
  538. check_class_member_name_conflict(p_class, member.variable->identifier->name, member.variable);
  539. GDScriptParser::DataType datatype;
  540. datatype.kind = GDScriptParser::DataType::VARIANT;
  541. datatype.type_source = GDScriptParser::DataType::UNDETECTED;
  542. GDScriptParser::DataType specified_type;
  543. if (member.variable->datatype_specifier != nullptr) {
  544. specified_type = resolve_datatype(member.variable->datatype_specifier);
  545. specified_type.is_meta_type = false;
  546. }
  547. if (member.variable->initializer != nullptr) {
  548. member.variable->set_datatype(datatype); // Allow recursive usage.
  549. reduce_expression(member.variable->initializer);
  550. if ((member.variable->infer_datatype || (member.variable->datatype_specifier != nullptr && specified_type.has_container_element_type())) && member.variable->initializer->type == GDScriptParser::Node::ARRAY) {
  551. // Typed array.
  552. GDScriptParser::ArrayNode *array = static_cast<GDScriptParser::ArrayNode *>(member.variable->initializer);
  553. // Can only infer typed array if it has elements.
  554. if ((member.variable->infer_datatype && array->elements.size() > 0) || member.variable->datatype_specifier != nullptr) {
  555. update_array_literal_element_type(specified_type, array);
  556. }
  557. }
  558. datatype = member.variable->initializer->get_datatype();
  559. if (datatype.type_source != GDScriptParser::DataType::UNDETECTED) {
  560. datatype.type_source = GDScriptParser::DataType::INFERRED;
  561. }
  562. }
  563. if (member.variable->datatype_specifier != nullptr) {
  564. datatype = specified_type;
  565. if (member.variable->initializer != nullptr) {
  566. if (!is_type_compatible(datatype, member.variable->initializer->get_datatype(), true)) {
  567. // Try reverse test since it can be a masked subtype.
  568. if (!is_type_compatible(member.variable->initializer->get_datatype(), datatype, true)) {
  569. push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", member.variable->initializer->get_datatype().to_string(), datatype.to_string()), member.variable->initializer);
  570. } else {
  571. // TODO: Add warning.
  572. mark_node_unsafe(member.variable->initializer);
  573. member.variable->use_conversion_assign = true;
  574. }
  575. } else if (datatype.builtin_type == Variant::INT && member.variable->initializer->get_datatype().builtin_type == Variant::FLOAT) {
  576. #ifdef DEBUG_ENABLED
  577. parser->push_warning(member.variable->initializer, GDScriptWarning::NARROWING_CONVERSION);
  578. #endif
  579. }
  580. if (member.variable->initializer->get_datatype().is_variant()) {
  581. // TODO: Warn unsafe assign.
  582. mark_node_unsafe(member.variable->initializer);
  583. member.variable->use_conversion_assign = true;
  584. }
  585. }
  586. } else if (member.variable->infer_datatype) {
  587. if (member.variable->initializer == nullptr) {
  588. push_error(vformat(R"(Cannot infer the type of "%s" variable because there's no default value.)", member.variable->identifier->name), member.variable->identifier);
  589. } else if (!datatype.is_set() || datatype.has_no_type()) {
  590. push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value doesn't have a set type.)", member.variable->identifier->name), member.variable->initializer);
  591. } else if (datatype.is_variant()) {
  592. push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value is Variant. Use explicit "Variant" type if this is intended.)", member.variable->identifier->name), member.variable->initializer);
  593. } else if (datatype.builtin_type == Variant::NIL) {
  594. push_error(vformat(R"(Cannot infer the type of "%s" variable because the initial value is "null".)", member.variable->identifier->name), member.variable->initializer);
  595. }
  596. datatype.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  597. }
  598. datatype.is_constant = false;
  599. member.variable->set_datatype(datatype);
  600. // Apply annotations.
  601. for (GDScriptParser::AnnotationNode *&E : member.variable->annotations) {
  602. E->apply(parser, member.variable);
  603. }
  604. } break;
  605. case GDScriptParser::ClassNode::Member::CONSTANT: {
  606. check_class_member_name_conflict(p_class, member.constant->identifier->name, member.constant);
  607. reduce_expression(member.constant->initializer);
  608. GDScriptParser::DataType specified_type;
  609. if (member.constant->datatype_specifier != nullptr) {
  610. specified_type = resolve_datatype(member.constant->datatype_specifier);
  611. specified_type.is_meta_type = false;
  612. }
  613. GDScriptParser::DataType datatype;
  614. if (member.constant->initializer) {
  615. datatype = member.constant->initializer->get_datatype();
  616. if (member.constant->initializer->type == GDScriptParser::Node::ARRAY) {
  617. GDScriptParser::ArrayNode *array = static_cast<GDScriptParser::ArrayNode *>(member.constant->initializer);
  618. const_fold_array(array);
  619. // Can only infer typed array if it has elements.
  620. if (array->elements.size() > 0 || (member.constant->datatype_specifier != nullptr && specified_type.has_container_element_type())) {
  621. update_array_literal_element_type(specified_type, array);
  622. }
  623. } else if (member.constant->initializer->type == GDScriptParser::Node::DICTIONARY) {
  624. const_fold_dictionary(static_cast<GDScriptParser::DictionaryNode *>(member.constant->initializer));
  625. }
  626. if (!member.constant->initializer->is_constant) {
  627. push_error(R"(Initializer for a constant must be a constant expression.)", member.constant->initializer);
  628. }
  629. if (member.constant->datatype_specifier != nullptr) {
  630. datatype = specified_type;
  631. if (!is_type_compatible(datatype, member.constant->initializer->get_datatype(), true)) {
  632. push_error(vformat(R"(Value of type "%s" cannot be initialized to constant of type "%s".)", member.constant->initializer->get_datatype().to_string(), datatype.to_string()), member.constant->initializer);
  633. } else if (datatype.builtin_type == Variant::INT && member.constant->initializer->get_datatype().builtin_type == Variant::FLOAT) {
  634. #ifdef DEBUG_ENABLED
  635. parser->push_warning(member.constant->initializer, GDScriptWarning::NARROWING_CONVERSION);
  636. #endif
  637. }
  638. }
  639. }
  640. datatype.is_constant = true;
  641. member.constant->set_datatype(datatype);
  642. // Apply annotations.
  643. for (GDScriptParser::AnnotationNode *&E : member.constant->annotations) {
  644. E->apply(parser, member.constant);
  645. }
  646. } break;
  647. case GDScriptParser::ClassNode::Member::SIGNAL: {
  648. check_class_member_name_conflict(p_class, member.signal->identifier->name, member.signal);
  649. for (int j = 0; j < member.signal->parameters.size(); j++) {
  650. GDScriptParser::DataType signal_type = resolve_datatype(member.signal->parameters[j]->datatype_specifier);
  651. signal_type.is_meta_type = false;
  652. member.signal->parameters[j]->set_datatype(signal_type);
  653. }
  654. // TODO: Make MethodInfo from signal.
  655. GDScriptParser::DataType signal_type;
  656. signal_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  657. signal_type.kind = GDScriptParser::DataType::BUILTIN;
  658. signal_type.builtin_type = Variant::SIGNAL;
  659. member.signal->set_datatype(signal_type);
  660. // Apply annotations.
  661. for (GDScriptParser::AnnotationNode *&E : member.signal->annotations) {
  662. E->apply(parser, member.signal);
  663. }
  664. } break;
  665. case GDScriptParser::ClassNode::Member::ENUM: {
  666. check_class_member_name_conflict(p_class, member.m_enum->identifier->name, member.m_enum);
  667. GDScriptParser::DataType enum_type;
  668. enum_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  669. enum_type.kind = GDScriptParser::DataType::ENUM;
  670. enum_type.builtin_type = Variant::DICTIONARY;
  671. enum_type.enum_type = member.m_enum->identifier->name;
  672. enum_type.native_type = p_class->fqcn + "." + member.m_enum->identifier->name;
  673. enum_type.is_meta_type = true;
  674. enum_type.is_constant = true;
  675. // Enums can't be nested, so we can safely override this.
  676. current_enum = member.m_enum;
  677. for (int j = 0; j < member.m_enum->values.size(); j++) {
  678. GDScriptParser::EnumNode::Value &element = member.m_enum->values.write[j];
  679. if (element.custom_value) {
  680. reduce_expression(element.custom_value);
  681. if (!element.custom_value->is_constant) {
  682. push_error(R"(Enum values must be constant.)", element.custom_value);
  683. } else if (element.custom_value->reduced_value.get_type() != Variant::INT) {
  684. push_error(R"(Enum values must be integers.)", element.custom_value);
  685. } else {
  686. element.value = element.custom_value->reduced_value;
  687. element.resolved = true;
  688. }
  689. } else {
  690. if (element.index > 0) {
  691. element.value = element.parent_enum->values[element.index - 1].value + 1;
  692. } else {
  693. element.value = 0;
  694. }
  695. element.resolved = true;
  696. }
  697. enum_type.enum_values[element.identifier->name] = element.value;
  698. }
  699. current_enum = nullptr;
  700. member.m_enum->set_datatype(enum_type);
  701. // Apply annotations.
  702. for (GDScriptParser::AnnotationNode *&E : member.m_enum->annotations) {
  703. E->apply(parser, member.m_enum);
  704. }
  705. } break;
  706. case GDScriptParser::ClassNode::Member::FUNCTION:
  707. resolve_function_signature(member.function);
  708. break;
  709. case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
  710. if (member.enum_value.custom_value) {
  711. check_class_member_name_conflict(p_class, member.enum_value.identifier->name, member.enum_value.custom_value);
  712. current_enum = member.enum_value.parent_enum;
  713. reduce_expression(member.enum_value.custom_value);
  714. current_enum = nullptr;
  715. if (!member.enum_value.custom_value->is_constant) {
  716. push_error(R"(Enum values must be constant.)", member.enum_value.custom_value);
  717. } else if (member.enum_value.custom_value->reduced_value.get_type() != Variant::INT) {
  718. push_error(R"(Enum values must be integers.)", member.enum_value.custom_value);
  719. } else {
  720. member.enum_value.value = member.enum_value.custom_value->reduced_value;
  721. member.enum_value.resolved = true;
  722. }
  723. } else {
  724. check_class_member_name_conflict(p_class, member.enum_value.identifier->name, member.enum_value.parent_enum);
  725. if (member.enum_value.index > 0) {
  726. member.enum_value.value = member.enum_value.parent_enum->values[member.enum_value.index - 1].value + 1;
  727. } else {
  728. member.enum_value.value = 0;
  729. }
  730. member.enum_value.resolved = true;
  731. }
  732. // Also update the original references.
  733. member.enum_value.parent_enum->values.write[member.enum_value.index] = member.enum_value;
  734. p_class->members.write[i].enum_value = member.enum_value;
  735. } break;
  736. case GDScriptParser::ClassNode::Member::CLASS:
  737. check_class_member_name_conflict(p_class, member.m_class->identifier->name, member.m_class);
  738. break;
  739. case GDScriptParser::ClassNode::Member::UNDEFINED:
  740. ERR_PRINT("Trying to resolve undefined member.");
  741. break;
  742. }
  743. }
  744. // Recurse nested classes.
  745. for (int i = 0; i < p_class->members.size(); i++) {
  746. GDScriptParser::ClassNode::Member member = p_class->members[i];
  747. if (member.type != GDScriptParser::ClassNode::Member::CLASS) {
  748. continue;
  749. }
  750. resolve_class_interface(member.m_class);
  751. }
  752. parser->current_class = previous_class;
  753. }
  754. void GDScriptAnalyzer::resolve_class_body(GDScriptParser::ClassNode *p_class) {
  755. if (p_class->resolved_body) {
  756. return;
  757. }
  758. p_class->resolved_body = true;
  759. GDScriptParser::ClassNode *previous_class = parser->current_class;
  760. parser->current_class = p_class;
  761. // Do functions now.
  762. for (int i = 0; i < p_class->members.size(); i++) {
  763. GDScriptParser::ClassNode::Member member = p_class->members[i];
  764. if (member.type != GDScriptParser::ClassNode::Member::FUNCTION) {
  765. continue;
  766. }
  767. resolve_function_body(member.function);
  768. // Apply annotations.
  769. for (GDScriptParser::AnnotationNode *&E : member.function->annotations) {
  770. E->apply(parser, member.function);
  771. }
  772. }
  773. parser->current_class = previous_class;
  774. // Recurse nested classes.
  775. for (int i = 0; i < p_class->members.size(); i++) {
  776. GDScriptParser::ClassNode::Member member = p_class->members[i];
  777. if (member.type != GDScriptParser::ClassNode::Member::CLASS) {
  778. continue;
  779. }
  780. resolve_class_body(member.m_class);
  781. }
  782. // Check unused variables.
  783. for (int i = 0; i < p_class->members.size(); i++) {
  784. GDScriptParser::ClassNode::Member member = p_class->members[i];
  785. if (member.type != GDScriptParser::ClassNode::Member::VARIABLE) {
  786. continue;
  787. }
  788. #ifdef DEBUG_ENABLED
  789. if (member.variable->usages == 0 && String(member.variable->identifier->name).begins_with("_")) {
  790. parser->push_warning(member.variable->identifier, GDScriptWarning::UNUSED_PRIVATE_CLASS_VARIABLE, member.variable->identifier->name);
  791. }
  792. #endif
  793. }
  794. }
  795. void GDScriptAnalyzer::resolve_node(GDScriptParser::Node *p_node) {
  796. ERR_FAIL_COND_MSG(p_node == nullptr, "Trying to resolve type of a null node.");
  797. switch (p_node->type) {
  798. case GDScriptParser::Node::NONE:
  799. break; // Unreachable.
  800. case GDScriptParser::Node::CLASS:
  801. resolve_class_interface(static_cast<GDScriptParser::ClassNode *>(p_node));
  802. resolve_class_body(static_cast<GDScriptParser::ClassNode *>(p_node));
  803. break;
  804. case GDScriptParser::Node::CONSTANT:
  805. resolve_constant(static_cast<GDScriptParser::ConstantNode *>(p_node));
  806. break;
  807. case GDScriptParser::Node::FOR:
  808. resolve_for(static_cast<GDScriptParser::ForNode *>(p_node));
  809. break;
  810. case GDScriptParser::Node::FUNCTION:
  811. resolve_function_signature(static_cast<GDScriptParser::FunctionNode *>(p_node));
  812. resolve_function_body(static_cast<GDScriptParser::FunctionNode *>(p_node));
  813. break;
  814. case GDScriptParser::Node::IF:
  815. resolve_if(static_cast<GDScriptParser::IfNode *>(p_node));
  816. break;
  817. case GDScriptParser::Node::SUITE:
  818. resolve_suite(static_cast<GDScriptParser::SuiteNode *>(p_node));
  819. break;
  820. case GDScriptParser::Node::VARIABLE:
  821. resolve_variable(static_cast<GDScriptParser::VariableNode *>(p_node));
  822. break;
  823. case GDScriptParser::Node::WHILE:
  824. resolve_while(static_cast<GDScriptParser::WhileNode *>(p_node));
  825. break;
  826. case GDScriptParser::Node::ANNOTATION:
  827. resolve_annotation(static_cast<GDScriptParser::AnnotationNode *>(p_node));
  828. break;
  829. case GDScriptParser::Node::ASSERT:
  830. resolve_assert(static_cast<GDScriptParser::AssertNode *>(p_node));
  831. break;
  832. case GDScriptParser::Node::MATCH:
  833. resolve_match(static_cast<GDScriptParser::MatchNode *>(p_node));
  834. break;
  835. case GDScriptParser::Node::MATCH_BRANCH:
  836. resolve_match_branch(static_cast<GDScriptParser::MatchBranchNode *>(p_node), nullptr);
  837. break;
  838. case GDScriptParser::Node::PARAMETER:
  839. resolve_parameter(static_cast<GDScriptParser::ParameterNode *>(p_node));
  840. break;
  841. case GDScriptParser::Node::PATTERN:
  842. resolve_match_pattern(static_cast<GDScriptParser::PatternNode *>(p_node), nullptr);
  843. break;
  844. case GDScriptParser::Node::RETURN:
  845. resolve_return(static_cast<GDScriptParser::ReturnNode *>(p_node));
  846. break;
  847. case GDScriptParser::Node::TYPE:
  848. resolve_datatype(static_cast<GDScriptParser::TypeNode *>(p_node));
  849. break;
  850. // Resolving expression is the same as reducing them.
  851. case GDScriptParser::Node::ARRAY:
  852. case GDScriptParser::Node::ASSIGNMENT:
  853. case GDScriptParser::Node::AWAIT:
  854. case GDScriptParser::Node::BINARY_OPERATOR:
  855. case GDScriptParser::Node::CALL:
  856. case GDScriptParser::Node::CAST:
  857. case GDScriptParser::Node::DICTIONARY:
  858. case GDScriptParser::Node::GET_NODE:
  859. case GDScriptParser::Node::IDENTIFIER:
  860. case GDScriptParser::Node::LAMBDA:
  861. case GDScriptParser::Node::LITERAL:
  862. case GDScriptParser::Node::PRELOAD:
  863. case GDScriptParser::Node::SELF:
  864. case GDScriptParser::Node::SUBSCRIPT:
  865. case GDScriptParser::Node::TERNARY_OPERATOR:
  866. case GDScriptParser::Node::UNARY_OPERATOR:
  867. reduce_expression(static_cast<GDScriptParser::ExpressionNode *>(p_node));
  868. break;
  869. case GDScriptParser::Node::BREAK:
  870. case GDScriptParser::Node::BREAKPOINT:
  871. case GDScriptParser::Node::CONTINUE:
  872. case GDScriptParser::Node::ENUM:
  873. case GDScriptParser::Node::PASS:
  874. case GDScriptParser::Node::SIGNAL:
  875. // Nothing to do.
  876. break;
  877. }
  878. }
  879. void GDScriptAnalyzer::resolve_annotation(GDScriptParser::AnnotationNode *p_annotation) {
  880. // TODO: Add second validation function for annotations, so they can use checked types.
  881. }
  882. void GDScriptAnalyzer::resolve_function_signature(GDScriptParser::FunctionNode *p_function) {
  883. if (p_function->resolved_signature) {
  884. return;
  885. }
  886. p_function->resolved_signature = true;
  887. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  888. parser->current_function = p_function;
  889. for (int i = 0; i < p_function->parameters.size(); i++) {
  890. resolve_parameter(p_function->parameters[i]);
  891. #ifdef DEBUG_ENABLED
  892. if (p_function->parameters[i]->usages == 0 && !String(p_function->parameters[i]->identifier->name).begins_with("_")) {
  893. parser->push_warning(p_function->parameters[i]->identifier, GDScriptWarning::UNUSED_PARAMETER, p_function->identifier->name, p_function->parameters[i]->identifier->name);
  894. }
  895. is_shadowing(p_function->parameters[i]->identifier, "function parameter");
  896. #endif // DEBUG_ENABLED
  897. #ifdef TOOLS_ENABLED
  898. if (p_function->parameters[i]->default_value && p_function->parameters[i]->default_value->is_constant) {
  899. p_function->default_arg_values.push_back(p_function->parameters[i]->default_value->reduced_value);
  900. }
  901. #endif // TOOLS_ENABLED
  902. }
  903. if (p_function->identifier->name == "_init") {
  904. // Constructor.
  905. GDScriptParser::DataType return_type = parser->current_class->get_datatype();
  906. return_type.is_meta_type = false;
  907. p_function->set_datatype(return_type);
  908. if (p_function->return_type) {
  909. push_error("Constructor cannot have an explicit return type.", p_function->return_type);
  910. }
  911. } else {
  912. GDScriptParser::DataType return_type = resolve_datatype(p_function->return_type);
  913. p_function->set_datatype(return_type);
  914. }
  915. parser->current_function = previous_function;
  916. }
  917. void GDScriptAnalyzer::resolve_function_body(GDScriptParser::FunctionNode *p_function) {
  918. if (p_function->resolved_body) {
  919. return;
  920. }
  921. p_function->resolved_body = true;
  922. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  923. parser->current_function = p_function;
  924. resolve_suite(p_function->body);
  925. GDScriptParser::DataType return_type = p_function->body->get_datatype();
  926. if (p_function->get_datatype().has_no_type() && return_type.is_set()) {
  927. // Use the suite inferred type if return isn't explicitly set.
  928. return_type.type_source = GDScriptParser::DataType::INFERRED;
  929. p_function->set_datatype(p_function->body->get_datatype());
  930. } else if (p_function->get_datatype().is_hard_type() && (p_function->get_datatype().kind != GDScriptParser::DataType::BUILTIN || p_function->get_datatype().builtin_type != Variant::NIL)) {
  931. if (!p_function->body->has_return && p_function->identifier->name != GDScriptLanguage::get_singleton()->strings._init) {
  932. push_error(R"(Not all code paths return a value.)", p_function);
  933. }
  934. }
  935. parser->current_function = previous_function;
  936. }
  937. void GDScriptAnalyzer::decide_suite_type(GDScriptParser::Node *p_suite, GDScriptParser::Node *p_statement) {
  938. if (p_statement == nullptr) {
  939. return;
  940. }
  941. switch (p_statement->type) {
  942. case GDScriptParser::Node::IF:
  943. case GDScriptParser::Node::FOR:
  944. case GDScriptParser::Node::MATCH:
  945. case GDScriptParser::Node::PATTERN:
  946. case GDScriptParser::Node::RETURN:
  947. case GDScriptParser::Node::WHILE:
  948. // Use return or nested suite type as this suite type.
  949. if (p_suite->get_datatype().is_set() && (p_suite->get_datatype() != p_statement->get_datatype())) {
  950. // Mixed types.
  951. // TODO: This could use the common supertype instead.
  952. p_suite->datatype.kind = GDScriptParser::DataType::VARIANT;
  953. p_suite->datatype.type_source = GDScriptParser::DataType::UNDETECTED;
  954. } else {
  955. p_suite->set_datatype(p_statement->get_datatype());
  956. p_suite->datatype.type_source = GDScriptParser::DataType::INFERRED;
  957. }
  958. break;
  959. default:
  960. break;
  961. }
  962. }
  963. void GDScriptAnalyzer::resolve_suite(GDScriptParser::SuiteNode *p_suite) {
  964. for (int i = 0; i < p_suite->statements.size(); i++) {
  965. GDScriptParser::Node *stmt = p_suite->statements[i];
  966. resolve_node(stmt);
  967. decide_suite_type(p_suite, stmt);
  968. }
  969. }
  970. void GDScriptAnalyzer::resolve_if(GDScriptParser::IfNode *p_if) {
  971. reduce_expression(p_if->condition);
  972. resolve_suite(p_if->true_block);
  973. p_if->set_datatype(p_if->true_block->get_datatype());
  974. if (p_if->false_block != nullptr) {
  975. resolve_suite(p_if->false_block);
  976. decide_suite_type(p_if, p_if->false_block);
  977. }
  978. }
  979. void GDScriptAnalyzer::resolve_for(GDScriptParser::ForNode *p_for) {
  980. bool list_resolved = false;
  981. // Optimize constant range() call to not allocate an array.
  982. // Use int, Vector2, Vector3 instead, which also can be used as range iterators.
  983. if (p_for->list && p_for->list->type == GDScriptParser::Node::CALL) {
  984. GDScriptParser::CallNode *call = static_cast<GDScriptParser::CallNode *>(p_for->list);
  985. GDScriptParser::Node::Type callee_type = call->get_callee_type();
  986. if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  987. GDScriptParser::IdentifierNode *callee = static_cast<GDScriptParser::IdentifierNode *>(call->callee);
  988. if (callee->name == "range") {
  989. list_resolved = true;
  990. if (call->arguments.size() < 1) {
  991. push_error(R"*(Invalid call for "range()" function. Expected at least 1 argument, none given.)*", call->callee);
  992. } else if (call->arguments.size() > 3) {
  993. push_error(vformat(R"*(Invalid call for "range()" function. Expected at most 3 arguments, %d given.)*", call->arguments.size()), call->callee);
  994. } else {
  995. // Now we can optimize it.
  996. bool all_is_constant = true;
  997. Vector<Variant> args;
  998. args.resize(call->arguments.size());
  999. for (int i = 0; i < call->arguments.size(); i++) {
  1000. reduce_expression(call->arguments[i]);
  1001. if (!call->arguments[i]->is_constant) {
  1002. all_is_constant = false;
  1003. } else if (all_is_constant) {
  1004. args.write[i] = call->arguments[i]->reduced_value;
  1005. }
  1006. GDScriptParser::DataType arg_type = call->arguments[i]->get_datatype();
  1007. if (!arg_type.is_variant()) {
  1008. if (arg_type.kind != GDScriptParser::DataType::BUILTIN) {
  1009. all_is_constant = false;
  1010. push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, arg_type.to_string()), call->arguments[i]);
  1011. } else if (arg_type.builtin_type != Variant::INT && arg_type.builtin_type != Variant::FLOAT) {
  1012. all_is_constant = false;
  1013. push_error(vformat(R"*(Invalid argument for "range()" call. Argument %d should be int or float but "%s" was given.)*", i + 1, arg_type.to_string()), call->arguments[i]);
  1014. }
  1015. }
  1016. }
  1017. Variant reduced;
  1018. if (all_is_constant) {
  1019. switch (args.size()) {
  1020. case 1:
  1021. reduced = args[0];
  1022. break;
  1023. case 2:
  1024. reduced = Vector2i(args[0], args[1]);
  1025. break;
  1026. case 3:
  1027. reduced = Vector3i(args[0], args[1], args[2]);
  1028. break;
  1029. }
  1030. p_for->list->is_constant = true;
  1031. p_for->list->reduced_value = reduced;
  1032. }
  1033. }
  1034. if (p_for->list->is_constant) {
  1035. p_for->list->set_datatype(type_from_variant(p_for->list->reduced_value, p_for->list));
  1036. } else {
  1037. GDScriptParser::DataType list_type;
  1038. list_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1039. list_type.kind = GDScriptParser::DataType::BUILTIN;
  1040. list_type.builtin_type = Variant::ARRAY;
  1041. p_for->list->set_datatype(list_type);
  1042. }
  1043. }
  1044. }
  1045. }
  1046. if (!list_resolved) {
  1047. resolve_node(p_for->list);
  1048. }
  1049. // TODO: If list is a typed array, the variable should be an element.
  1050. // Also applicable for constant range() (so variable is int or float).
  1051. resolve_suite(p_for->loop);
  1052. p_for->set_datatype(p_for->loop->get_datatype());
  1053. #ifdef DEBUG_ENABLED
  1054. if (p_for->variable) {
  1055. is_shadowing(p_for->variable, R"("for" iterator variable)");
  1056. }
  1057. #endif
  1058. }
  1059. void GDScriptAnalyzer::resolve_while(GDScriptParser::WhileNode *p_while) {
  1060. resolve_node(p_while->condition);
  1061. resolve_suite(p_while->loop);
  1062. p_while->set_datatype(p_while->loop->get_datatype());
  1063. }
  1064. void GDScriptAnalyzer::resolve_variable(GDScriptParser::VariableNode *p_variable) {
  1065. GDScriptParser::DataType type;
  1066. type.kind = GDScriptParser::DataType::VARIANT; // By default.
  1067. GDScriptParser::DataType specified_type;
  1068. if (p_variable->datatype_specifier != nullptr) {
  1069. specified_type = resolve_datatype(p_variable->datatype_specifier);
  1070. specified_type.is_meta_type = false;
  1071. }
  1072. if (p_variable->initializer != nullptr) {
  1073. reduce_expression(p_variable->initializer);
  1074. if ((p_variable->infer_datatype || (p_variable->datatype_specifier != nullptr && specified_type.has_container_element_type())) && p_variable->initializer->type == GDScriptParser::Node::ARRAY) {
  1075. // Typed array.
  1076. GDScriptParser::ArrayNode *array = static_cast<GDScriptParser::ArrayNode *>(p_variable->initializer);
  1077. // Can only infer typed array if it has elements.
  1078. if ((p_variable->infer_datatype && array->elements.size() > 0) || p_variable->datatype_specifier != nullptr) {
  1079. update_array_literal_element_type(specified_type, array);
  1080. }
  1081. }
  1082. type = p_variable->initializer->get_datatype();
  1083. if (p_variable->infer_datatype) {
  1084. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1085. if (type.has_no_type()) {
  1086. push_error(vformat(R"(Could not infer the type of the variable "%s" because the initial value does not have a set type.)", p_variable->identifier->name), p_variable->initializer);
  1087. } else if (type.is_variant()) {
  1088. push_error(vformat(R"(Could not infer the type of the variable "%s" because the initial value is a variant. Use explicit "Variant" type if this is intended.)", p_variable->identifier->name), p_variable->initializer);
  1089. } else if (type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL) {
  1090. push_error(vformat(R"(Could not infer the type of the variable "%s" because the initial value is "null".)", p_variable->identifier->name), p_variable->initializer);
  1091. }
  1092. } else {
  1093. type.type_source = GDScriptParser::DataType::INFERRED;
  1094. }
  1095. #ifdef DEBUG_ENABLED
  1096. if (p_variable->initializer->type == GDScriptParser::Node::CALL && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL) {
  1097. parser->push_warning(p_variable->initializer, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_variable->initializer)->function_name);
  1098. }
  1099. #endif
  1100. }
  1101. if (p_variable->datatype_specifier != nullptr) {
  1102. type = specified_type;
  1103. type.is_meta_type = false;
  1104. if (p_variable->initializer != nullptr) {
  1105. if (!is_type_compatible(type, p_variable->initializer->get_datatype(), true)) {
  1106. // Try reverse test since it can be a masked subtype.
  1107. if (!is_type_compatible(p_variable->initializer->get_datatype(), type, true)) {
  1108. push_error(vformat(R"(Value of type "%s" cannot be assigned to a variable of type "%s".)", p_variable->initializer->get_datatype().to_string(), type.to_string()), p_variable->initializer);
  1109. } else {
  1110. // TODO: Add warning.
  1111. mark_node_unsafe(p_variable->initializer);
  1112. p_variable->use_conversion_assign = true;
  1113. }
  1114. #ifdef DEBUG_ENABLED
  1115. } else if (type.builtin_type == Variant::INT && p_variable->initializer->get_datatype().builtin_type == Variant::FLOAT) {
  1116. parser->push_warning(p_variable->initializer, GDScriptWarning::NARROWING_CONVERSION);
  1117. #endif
  1118. }
  1119. if (p_variable->initializer->get_datatype().is_variant()) {
  1120. // TODO: Warn unsafe assign.
  1121. mark_node_unsafe(p_variable->initializer);
  1122. p_variable->use_conversion_assign = true;
  1123. }
  1124. }
  1125. } else if (p_variable->infer_datatype) {
  1126. if (type.has_no_type()) {
  1127. push_error(vformat(R"(Cannot infer the type of variable "%s" because the initial value doesn't have a set type.)", p_variable->identifier->name), p_variable->identifier);
  1128. }
  1129. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1130. }
  1131. type.is_constant = false;
  1132. p_variable->set_datatype(type);
  1133. #ifdef DEBUG_ENABLED
  1134. if (p_variable->usages == 0 && !String(p_variable->identifier->name).begins_with("_")) {
  1135. parser->push_warning(p_variable, GDScriptWarning::UNUSED_VARIABLE, p_variable->identifier->name);
  1136. } else if (p_variable->assignments == 0) {
  1137. parser->push_warning(p_variable, GDScriptWarning::UNASSIGNED_VARIABLE, p_variable->identifier->name);
  1138. }
  1139. is_shadowing(p_variable->identifier, "variable");
  1140. #endif
  1141. }
  1142. void GDScriptAnalyzer::resolve_constant(GDScriptParser::ConstantNode *p_constant) {
  1143. GDScriptParser::DataType type;
  1144. if (p_constant->initializer != nullptr) {
  1145. reduce_expression(p_constant->initializer);
  1146. if (p_constant->initializer->type == GDScriptParser::Node::ARRAY) {
  1147. const_fold_array(static_cast<GDScriptParser::ArrayNode *>(p_constant->initializer));
  1148. } else if (p_constant->initializer->type == GDScriptParser::Node::DICTIONARY) {
  1149. const_fold_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_constant->initializer));
  1150. }
  1151. if (!p_constant->initializer->is_constant) {
  1152. push_error(vformat(R"(Assigned value for constant "%s" isn't a constant expression.)", p_constant->identifier->name), p_constant->initializer);
  1153. }
  1154. type = p_constant->initializer->get_datatype();
  1155. #ifdef DEBUG_ENABLED
  1156. if (p_constant->initializer->type == GDScriptParser::Node::CALL && type.kind == GDScriptParser::DataType::BUILTIN && type.builtin_type == Variant::NIL) {
  1157. parser->push_warning(p_constant->initializer, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_constant->initializer)->function_name);
  1158. }
  1159. #endif
  1160. }
  1161. if (p_constant->datatype_specifier != nullptr) {
  1162. GDScriptParser::DataType explicit_type = resolve_datatype(p_constant->datatype_specifier);
  1163. explicit_type.is_meta_type = false;
  1164. if (!is_type_compatible(explicit_type, type)) {
  1165. push_error(vformat(R"(Assigned value for constant "%s" has type %s which is not compatible with defined type %s.)", p_constant->identifier->name, type.to_string(), explicit_type.to_string()), p_constant->initializer);
  1166. #ifdef DEBUG_ENABLED
  1167. } else if (explicit_type.builtin_type == Variant::INT && type.builtin_type == Variant::FLOAT) {
  1168. parser->push_warning(p_constant->initializer, GDScriptWarning::NARROWING_CONVERSION);
  1169. #endif
  1170. }
  1171. type = explicit_type;
  1172. } else if (p_constant->infer_datatype) {
  1173. if (type.has_no_type()) {
  1174. push_error(vformat(R"(Cannot infer the type of constant "%s" because the initial value doesn't have a set type.)", p_constant->identifier->name), p_constant->identifier);
  1175. }
  1176. type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1177. }
  1178. type.is_constant = true;
  1179. p_constant->set_datatype(type);
  1180. #ifdef DEBUG_ENABLED
  1181. if (p_constant->usages == 0) {
  1182. parser->push_warning(p_constant, GDScriptWarning::UNUSED_LOCAL_CONSTANT, p_constant->identifier->name);
  1183. }
  1184. is_shadowing(p_constant->identifier, "constant");
  1185. #endif
  1186. }
  1187. void GDScriptAnalyzer::resolve_assert(GDScriptParser::AssertNode *p_assert) {
  1188. reduce_expression(p_assert->condition);
  1189. if (p_assert->message != nullptr) {
  1190. reduce_expression(p_assert->message);
  1191. if (!p_assert->message->is_constant || p_assert->message->reduced_value.get_type() != Variant::STRING) {
  1192. push_error(R"(Expected constant string for assert error message.)", p_assert->message);
  1193. }
  1194. }
  1195. p_assert->set_datatype(p_assert->condition->get_datatype());
  1196. #ifdef DEBUG_ENABLED
  1197. if (p_assert->condition->is_constant) {
  1198. if (p_assert->condition->reduced_value.booleanize()) {
  1199. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_TRUE);
  1200. } else {
  1201. parser->push_warning(p_assert->condition, GDScriptWarning::ASSERT_ALWAYS_FALSE);
  1202. }
  1203. }
  1204. #endif
  1205. }
  1206. void GDScriptAnalyzer::resolve_match(GDScriptParser::MatchNode *p_match) {
  1207. reduce_expression(p_match->test);
  1208. for (int i = 0; i < p_match->branches.size(); i++) {
  1209. resolve_match_branch(p_match->branches[i], p_match->test);
  1210. decide_suite_type(p_match, p_match->branches[i]);
  1211. }
  1212. }
  1213. void GDScriptAnalyzer::resolve_match_branch(GDScriptParser::MatchBranchNode *p_match_branch, GDScriptParser::ExpressionNode *p_match_test) {
  1214. for (int i = 0; i < p_match_branch->patterns.size(); i++) {
  1215. resolve_match_pattern(p_match_branch->patterns[i], p_match_test);
  1216. }
  1217. resolve_suite(p_match_branch->block);
  1218. decide_suite_type(p_match_branch, p_match_branch->block);
  1219. }
  1220. void GDScriptAnalyzer::resolve_match_pattern(GDScriptParser::PatternNode *p_match_pattern, GDScriptParser::ExpressionNode *p_match_test) {
  1221. if (p_match_pattern == nullptr) {
  1222. return;
  1223. }
  1224. GDScriptParser::DataType result;
  1225. switch (p_match_pattern->pattern_type) {
  1226. case GDScriptParser::PatternNode::PT_LITERAL:
  1227. if (p_match_pattern->literal) {
  1228. reduce_literal(p_match_pattern->literal);
  1229. result = p_match_pattern->literal->get_datatype();
  1230. }
  1231. break;
  1232. case GDScriptParser::PatternNode::PT_EXPRESSION:
  1233. if (p_match_pattern->expression) {
  1234. reduce_expression(p_match_pattern->expression);
  1235. if (!p_match_pattern->expression->is_constant) {
  1236. push_error(R"(Expression in match pattern must be a constant.)", p_match_pattern->expression);
  1237. }
  1238. result = p_match_pattern->expression->get_datatype();
  1239. }
  1240. break;
  1241. case GDScriptParser::PatternNode::PT_BIND:
  1242. if (p_match_test != nullptr) {
  1243. result = p_match_test->get_datatype();
  1244. } else {
  1245. result.kind = GDScriptParser::DataType::VARIANT;
  1246. }
  1247. p_match_pattern->bind->set_datatype(result);
  1248. #ifdef DEBUG_ENABLED
  1249. is_shadowing(p_match_pattern->bind, "pattern bind");
  1250. if (p_match_pattern->bind->usages == 0) {
  1251. parser->push_warning(p_match_pattern->bind, GDScriptWarning::UNASSIGNED_VARIABLE, p_match_pattern->bind->name);
  1252. }
  1253. #endif
  1254. break;
  1255. case GDScriptParser::PatternNode::PT_ARRAY:
  1256. for (int i = 0; i < p_match_pattern->array.size(); i++) {
  1257. resolve_match_pattern(p_match_pattern->array[i], nullptr);
  1258. decide_suite_type(p_match_pattern, p_match_pattern->array[i]);
  1259. }
  1260. result = p_match_pattern->get_datatype();
  1261. break;
  1262. case GDScriptParser::PatternNode::PT_DICTIONARY:
  1263. for (int i = 0; i < p_match_pattern->dictionary.size(); i++) {
  1264. if (p_match_pattern->dictionary[i].key) {
  1265. reduce_expression(p_match_pattern->dictionary[i].key);
  1266. if (!p_match_pattern->dictionary[i].key->is_constant) {
  1267. push_error(R"(Expression in dictionary pattern key must be a constant.)", p_match_pattern->expression);
  1268. }
  1269. }
  1270. if (p_match_pattern->dictionary[i].value_pattern) {
  1271. resolve_match_pattern(p_match_pattern->dictionary[i].value_pattern, nullptr);
  1272. decide_suite_type(p_match_pattern, p_match_pattern->dictionary[i].value_pattern);
  1273. }
  1274. }
  1275. result = p_match_pattern->get_datatype();
  1276. break;
  1277. case GDScriptParser::PatternNode::PT_WILDCARD:
  1278. case GDScriptParser::PatternNode::PT_REST:
  1279. result.kind = GDScriptParser::DataType::VARIANT;
  1280. break;
  1281. }
  1282. p_match_pattern->set_datatype(result);
  1283. }
  1284. void GDScriptAnalyzer::resolve_parameter(GDScriptParser::ParameterNode *p_parameter) {
  1285. GDScriptParser::DataType result;
  1286. result.kind = GDScriptParser::DataType::VARIANT;
  1287. if (p_parameter->default_value != nullptr) {
  1288. reduce_expression(p_parameter->default_value);
  1289. result = p_parameter->default_value->get_datatype();
  1290. if (p_parameter->infer_datatype) {
  1291. result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  1292. } else {
  1293. result.type_source = GDScriptParser::DataType::INFERRED;
  1294. }
  1295. result.is_constant = false;
  1296. }
  1297. if (p_parameter->datatype_specifier != nullptr) {
  1298. resolve_datatype(p_parameter->datatype_specifier);
  1299. result = p_parameter->datatype_specifier->get_datatype();
  1300. result.is_meta_type = false;
  1301. if (p_parameter->default_value != nullptr) {
  1302. if (!is_type_compatible(result, p_parameter->default_value->get_datatype())) {
  1303. push_error(vformat(R"(Type of default value for parameter "%s" (%s) is not compatible with parameter type (%s).)", p_parameter->identifier->name, p_parameter->default_value->get_datatype().to_string(), p_parameter->datatype_specifier->get_datatype().to_string()), p_parameter->default_value);
  1304. } else if (p_parameter->default_value->get_datatype().is_variant()) {
  1305. mark_node_unsafe(p_parameter);
  1306. }
  1307. }
  1308. }
  1309. p_parameter->set_datatype(result);
  1310. }
  1311. void GDScriptAnalyzer::resolve_return(GDScriptParser::ReturnNode *p_return) {
  1312. GDScriptParser::DataType result;
  1313. if (p_return->return_value != nullptr) {
  1314. reduce_expression(p_return->return_value);
  1315. if (p_return->return_value->type == GDScriptParser::Node::ARRAY) {
  1316. // Check if assigned value is an array literal, so we can make it a typed array too if appropriate.
  1317. if (parser->current_function->get_datatype().has_container_element_type() && p_return->return_value->type == GDScriptParser::Node::ARRAY) {
  1318. update_array_literal_element_type(parser->current_function->get_datatype(), static_cast<GDScriptParser::ArrayNode *>(p_return->return_value));
  1319. }
  1320. }
  1321. result = p_return->return_value->get_datatype();
  1322. } else {
  1323. // Return type is null by default.
  1324. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1325. result.kind = GDScriptParser::DataType::BUILTIN;
  1326. result.builtin_type = Variant::NIL;
  1327. result.is_constant = true;
  1328. }
  1329. GDScriptParser::DataType function_type = parser->current_function->get_datatype();
  1330. function_type.is_meta_type = false;
  1331. if (function_type.is_hard_type()) {
  1332. if (!is_type_compatible(function_type, result)) {
  1333. // Try other way. Okay but not safe.
  1334. if (!is_type_compatible(result, function_type)) {
  1335. push_error(vformat(R"(Cannot return value of type "%s" because the function return type is "%s".)", result.to_string(), function_type.to_string()), p_return);
  1336. } else {
  1337. // TODO: Add warning.
  1338. mark_node_unsafe(p_return);
  1339. }
  1340. #ifdef DEBUG_ENABLED
  1341. } else if (function_type.builtin_type == Variant::INT && result.builtin_type == Variant::FLOAT) {
  1342. parser->push_warning(p_return, GDScriptWarning::NARROWING_CONVERSION);
  1343. } else if (result.is_variant()) {
  1344. mark_node_unsafe(p_return);
  1345. #endif
  1346. }
  1347. }
  1348. p_return->set_datatype(result);
  1349. }
  1350. void GDScriptAnalyzer::reduce_expression(GDScriptParser::ExpressionNode *p_expression) {
  1351. // This one makes some magic happen.
  1352. if (p_expression == nullptr) {
  1353. return;
  1354. }
  1355. if (p_expression->reduced) {
  1356. // Don't do this more than once.
  1357. return;
  1358. }
  1359. p_expression->reduced = true;
  1360. switch (p_expression->type) {
  1361. case GDScriptParser::Node::ARRAY:
  1362. reduce_array(static_cast<GDScriptParser::ArrayNode *>(p_expression));
  1363. break;
  1364. case GDScriptParser::Node::ASSIGNMENT:
  1365. reduce_assignment(static_cast<GDScriptParser::AssignmentNode *>(p_expression));
  1366. break;
  1367. case GDScriptParser::Node::AWAIT:
  1368. reduce_await(static_cast<GDScriptParser::AwaitNode *>(p_expression));
  1369. break;
  1370. case GDScriptParser::Node::BINARY_OPERATOR:
  1371. reduce_binary_op(static_cast<GDScriptParser::BinaryOpNode *>(p_expression));
  1372. break;
  1373. case GDScriptParser::Node::CALL:
  1374. reduce_call(static_cast<GDScriptParser::CallNode *>(p_expression));
  1375. break;
  1376. case GDScriptParser::Node::CAST:
  1377. reduce_cast(static_cast<GDScriptParser::CastNode *>(p_expression));
  1378. break;
  1379. case GDScriptParser::Node::DICTIONARY:
  1380. reduce_dictionary(static_cast<GDScriptParser::DictionaryNode *>(p_expression));
  1381. break;
  1382. case GDScriptParser::Node::GET_NODE:
  1383. reduce_get_node(static_cast<GDScriptParser::GetNodeNode *>(p_expression));
  1384. break;
  1385. case GDScriptParser::Node::IDENTIFIER:
  1386. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_expression));
  1387. break;
  1388. case GDScriptParser::Node::LAMBDA:
  1389. reduce_lambda(static_cast<GDScriptParser::LambdaNode *>(p_expression));
  1390. break;
  1391. case GDScriptParser::Node::LITERAL:
  1392. reduce_literal(static_cast<GDScriptParser::LiteralNode *>(p_expression));
  1393. break;
  1394. case GDScriptParser::Node::PRELOAD:
  1395. reduce_preload(static_cast<GDScriptParser::PreloadNode *>(p_expression));
  1396. break;
  1397. case GDScriptParser::Node::SELF:
  1398. reduce_self(static_cast<GDScriptParser::SelfNode *>(p_expression));
  1399. break;
  1400. case GDScriptParser::Node::SUBSCRIPT:
  1401. reduce_subscript(static_cast<GDScriptParser::SubscriptNode *>(p_expression));
  1402. break;
  1403. case GDScriptParser::Node::TERNARY_OPERATOR:
  1404. reduce_ternary_op(static_cast<GDScriptParser::TernaryOpNode *>(p_expression));
  1405. break;
  1406. case GDScriptParser::Node::UNARY_OPERATOR:
  1407. reduce_unary_op(static_cast<GDScriptParser::UnaryOpNode *>(p_expression));
  1408. break;
  1409. // Non-expressions. Here only to make sure new nodes aren't forgotten.
  1410. case GDScriptParser::Node::NONE:
  1411. case GDScriptParser::Node::ANNOTATION:
  1412. case GDScriptParser::Node::ASSERT:
  1413. case GDScriptParser::Node::BREAK:
  1414. case GDScriptParser::Node::BREAKPOINT:
  1415. case GDScriptParser::Node::CLASS:
  1416. case GDScriptParser::Node::CONSTANT:
  1417. case GDScriptParser::Node::CONTINUE:
  1418. case GDScriptParser::Node::ENUM:
  1419. case GDScriptParser::Node::FOR:
  1420. case GDScriptParser::Node::FUNCTION:
  1421. case GDScriptParser::Node::IF:
  1422. case GDScriptParser::Node::MATCH:
  1423. case GDScriptParser::Node::MATCH_BRANCH:
  1424. case GDScriptParser::Node::PARAMETER:
  1425. case GDScriptParser::Node::PASS:
  1426. case GDScriptParser::Node::PATTERN:
  1427. case GDScriptParser::Node::RETURN:
  1428. case GDScriptParser::Node::SIGNAL:
  1429. case GDScriptParser::Node::SUITE:
  1430. case GDScriptParser::Node::TYPE:
  1431. case GDScriptParser::Node::VARIABLE:
  1432. case GDScriptParser::Node::WHILE:
  1433. ERR_FAIL_MSG("Reaching unreachable case");
  1434. }
  1435. }
  1436. void GDScriptAnalyzer::reduce_array(GDScriptParser::ArrayNode *p_array) {
  1437. for (int i = 0; i < p_array->elements.size(); i++) {
  1438. GDScriptParser::ExpressionNode *element = p_array->elements[i];
  1439. reduce_expression(element);
  1440. }
  1441. // It's array in any case.
  1442. GDScriptParser::DataType arr_type;
  1443. arr_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1444. arr_type.kind = GDScriptParser::DataType::BUILTIN;
  1445. arr_type.builtin_type = Variant::ARRAY;
  1446. arr_type.is_constant = true;
  1447. p_array->set_datatype(arr_type);
  1448. }
  1449. // When an array literal is stored (or passed as function argument) to a typed context, we then assume the array is typed.
  1450. // This function determines which type is that (if any).
  1451. void GDScriptAnalyzer::update_array_literal_element_type(const GDScriptParser::DataType &p_base_type, GDScriptParser::ArrayNode *p_array_literal) {
  1452. GDScriptParser::DataType array_type = p_array_literal->get_datatype();
  1453. if (p_array_literal->elements.size() == 0) {
  1454. // Empty array literal, just make the same type as the storage.
  1455. array_type.set_container_element_type(p_base_type.get_container_element_type());
  1456. } else {
  1457. // Check if elements match.
  1458. bool all_same_type = true;
  1459. bool all_have_type = true;
  1460. GDScriptParser::DataType element_type;
  1461. for (int i = 0; i < p_array_literal->elements.size(); i++) {
  1462. if (i == 0) {
  1463. element_type = p_array_literal->elements[0]->get_datatype();
  1464. } else {
  1465. GDScriptParser::DataType this_element_type = p_array_literal->elements[i]->get_datatype();
  1466. if (this_element_type.has_no_type()) {
  1467. all_same_type = false;
  1468. all_have_type = false;
  1469. break;
  1470. } else if (element_type != this_element_type) {
  1471. if (!is_type_compatible(element_type, this_element_type, false)) {
  1472. if (is_type_compatible(this_element_type, element_type, false)) {
  1473. // This element is a super-type to the previous type, so we use the super-type.
  1474. element_type = this_element_type;
  1475. } else {
  1476. // It's incompatible.
  1477. all_same_type = false;
  1478. break;
  1479. }
  1480. }
  1481. }
  1482. }
  1483. }
  1484. if (all_same_type) {
  1485. array_type.set_container_element_type(element_type);
  1486. } else if (all_have_type) {
  1487. push_error(vformat(R"(Variant array is not compatible with an array of type "%s".)", p_base_type.get_container_element_type().to_string()), p_array_literal);
  1488. }
  1489. }
  1490. // Update the type on the value itself.
  1491. p_array_literal->set_datatype(array_type);
  1492. }
  1493. void GDScriptAnalyzer::reduce_assignment(GDScriptParser::AssignmentNode *p_assignment) {
  1494. reduce_expression(p_assignment->assignee);
  1495. reduce_expression(p_assignment->assigned_value);
  1496. if (p_assignment->assigned_value == nullptr || p_assignment->assignee == nullptr) {
  1497. return;
  1498. }
  1499. GDScriptParser::DataType assignee_type = p_assignment->assignee->get_datatype();
  1500. // Check if assigned value is an array literal, so we can make it a typed array too if appropriate.
  1501. if (assignee_type.has_container_element_type() && p_assignment->assigned_value->type == GDScriptParser::Node::ARRAY) {
  1502. update_array_literal_element_type(assignee_type, static_cast<GDScriptParser::ArrayNode *>(p_assignment->assigned_value));
  1503. }
  1504. GDScriptParser::DataType assigned_value_type = p_assignment->assigned_value->get_datatype();
  1505. if (assignee_type.is_constant) {
  1506. push_error("Cannot assign a new value to a constant.", p_assignment->assignee);
  1507. }
  1508. if (!assignee_type.is_variant() && !assigned_value_type.is_variant()) {
  1509. bool compatible = true;
  1510. GDScriptParser::DataType op_type = assigned_value_type;
  1511. if (p_assignment->operation != GDScriptParser::AssignmentNode::OP_NONE) {
  1512. op_type = get_operation_type(p_assignment->variant_op, assignee_type, assigned_value_type, compatible, p_assignment->assigned_value);
  1513. }
  1514. if (compatible) {
  1515. compatible = is_type_compatible(assignee_type, op_type, true);
  1516. if (!compatible) {
  1517. if (assignee_type.is_hard_type()) {
  1518. // Try reverse test since it can be a masked subtype.
  1519. if (!is_type_compatible(op_type, assignee_type, true)) {
  1520. push_error(vformat(R"(Cannot assign a value of type "%s" to a target of type "%s".)", assigned_value_type.to_string(), assignee_type.to_string()), p_assignment->assigned_value);
  1521. } else {
  1522. // TODO: Add warning.
  1523. mark_node_unsafe(p_assignment);
  1524. p_assignment->use_conversion_assign = true;
  1525. }
  1526. } else {
  1527. // TODO: Warning in this case.
  1528. mark_node_unsafe(p_assignment);
  1529. p_assignment->use_conversion_assign = true;
  1530. }
  1531. }
  1532. } else {
  1533. push_error(vformat(R"(Invalid operands "%s" and "%s" for assignment operator.)", assignee_type.to_string(), assigned_value_type.to_string()), p_assignment);
  1534. }
  1535. }
  1536. if (assignee_type.has_no_type() || assigned_value_type.is_variant()) {
  1537. mark_node_unsafe(p_assignment);
  1538. if (assignee_type.is_hard_type()) {
  1539. p_assignment->use_conversion_assign = true;
  1540. }
  1541. }
  1542. if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {
  1543. // Change source type so it's not wrongly detected later.
  1544. GDScriptParser::IdentifierNode *identifier = static_cast<GDScriptParser::IdentifierNode *>(p_assignment->assignee);
  1545. switch (identifier->source) {
  1546. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE: {
  1547. GDScriptParser::DataType id_type = identifier->variable_source->get_datatype();
  1548. if (!id_type.is_hard_type()) {
  1549. id_type.kind = GDScriptParser::DataType::VARIANT;
  1550. id_type.type_source = GDScriptParser::DataType::UNDETECTED;
  1551. identifier->variable_source->set_datatype(id_type);
  1552. }
  1553. } break;
  1554. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE: {
  1555. GDScriptParser::DataType id_type = identifier->variable_source->get_datatype();
  1556. if (!id_type.is_hard_type()) {
  1557. id_type = assigned_value_type;
  1558. id_type.type_source = GDScriptParser::DataType::INFERRED;
  1559. id_type.is_constant = false;
  1560. identifier->variable_source->set_datatype(id_type);
  1561. }
  1562. } break;
  1563. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR: {
  1564. GDScriptParser::DataType id_type = identifier->bind_source->get_datatype();
  1565. if (!id_type.is_hard_type()) {
  1566. id_type = assigned_value_type;
  1567. id_type.type_source = GDScriptParser::DataType::INFERRED;
  1568. id_type.is_constant = false;
  1569. identifier->variable_source->set_datatype(id_type);
  1570. }
  1571. } break;
  1572. default:
  1573. // Nothing to do.
  1574. break;
  1575. }
  1576. }
  1577. #ifdef DEBUG_ENABLED
  1578. if (p_assignment->assigned_value->type == GDScriptParser::Node::CALL && assigned_value_type.kind == GDScriptParser::DataType::BUILTIN && assigned_value_type.builtin_type == Variant::NIL) {
  1579. parser->push_warning(p_assignment->assigned_value, GDScriptWarning::VOID_ASSIGNMENT, static_cast<GDScriptParser::CallNode *>(p_assignment->assigned_value)->function_name);
  1580. } else if (assignee_type.is_hard_type() && assignee_type.builtin_type == Variant::INT && assigned_value_type.builtin_type == Variant::FLOAT) {
  1581. parser->push_warning(p_assignment->assigned_value, GDScriptWarning::NARROWING_CONVERSION);
  1582. }
  1583. #endif
  1584. }
  1585. void GDScriptAnalyzer::reduce_await(GDScriptParser::AwaitNode *p_await) {
  1586. if (p_await->to_await == nullptr) {
  1587. GDScriptParser::DataType await_type;
  1588. await_type.kind = GDScriptParser::DataType::VARIANT;
  1589. p_await->set_datatype(await_type);
  1590. return;
  1591. }
  1592. if (p_await->to_await->type == GDScriptParser::Node::CALL) {
  1593. reduce_call(static_cast<GDScriptParser::CallNode *>(p_await->to_await), true);
  1594. } else {
  1595. reduce_expression(p_await->to_await);
  1596. }
  1597. p_await->is_constant = p_await->to_await->is_constant;
  1598. p_await->reduced_value = p_await->to_await->reduced_value;
  1599. GDScriptParser::DataType awaiting_type = p_await->to_await->get_datatype();
  1600. p_await->set_datatype(awaiting_type);
  1601. #ifdef DEBUG_ENABLED
  1602. if (!awaiting_type.is_coroutine && awaiting_type.builtin_type != Variant::SIGNAL) {
  1603. parser->push_warning(p_await, GDScriptWarning::REDUNDANT_AWAIT);
  1604. }
  1605. #endif
  1606. }
  1607. void GDScriptAnalyzer::reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_op) {
  1608. reduce_expression(p_binary_op->left_operand);
  1609. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST && p_binary_op->right_operand && p_binary_op->right_operand->type == GDScriptParser::Node::IDENTIFIER) {
  1610. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_binary_op->right_operand), true);
  1611. } else {
  1612. reduce_expression(p_binary_op->right_operand);
  1613. }
  1614. // TODO: Right operand must be a valid type with the `is` operator. Need to check here.
  1615. GDScriptParser::DataType left_type;
  1616. if (p_binary_op->left_operand) {
  1617. left_type = p_binary_op->left_operand->get_datatype();
  1618. }
  1619. GDScriptParser::DataType right_type;
  1620. if (p_binary_op->right_operand) {
  1621. right_type = p_binary_op->right_operand->get_datatype();
  1622. }
  1623. if (!left_type.is_set() || !right_type.is_set()) {
  1624. return;
  1625. }
  1626. #ifdef DEBUG_ENABLED
  1627. if (p_binary_op->variant_op == Variant::OP_DIVIDE && left_type.builtin_type == Variant::INT && right_type.builtin_type == Variant::INT) {
  1628. parser->push_warning(p_binary_op, GDScriptWarning::INTEGER_DIVISION);
  1629. }
  1630. #endif
  1631. if (p_binary_op->left_operand->is_constant && p_binary_op->right_operand->is_constant) {
  1632. p_binary_op->is_constant = true;
  1633. if (p_binary_op->variant_op < Variant::OP_MAX) {
  1634. bool valid = false;
  1635. Variant::evaluate(p_binary_op->variant_op, p_binary_op->left_operand->reduced_value, p_binary_op->right_operand->reduced_value, p_binary_op->reduced_value, valid);
  1636. if (!valid) {
  1637. if (p_binary_op->reduced_value.get_type() == Variant::STRING) {
  1638. push_error(vformat(R"(%s in operator %s.)", p_binary_op->reduced_value, Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op);
  1639. } else {
  1640. push_error(vformat(R"(Invalid operands to operator %s, %s and %s.)",
  1641. Variant::get_operator_name(p_binary_op->variant_op),
  1642. Variant::get_type_name(p_binary_op->left_operand->reduced_value.get_type()),
  1643. Variant::get_type_name(p_binary_op->right_operand->reduced_value.get_type())),
  1644. p_binary_op);
  1645. }
  1646. }
  1647. } else {
  1648. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
  1649. GDScriptParser::DataType test_type = right_type;
  1650. test_type.is_meta_type = false;
  1651. if (!is_type_compatible(test_type, p_binary_op->left_operand->get_datatype(), false)) {
  1652. push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)"), p_binary_op->left_operand);
  1653. p_binary_op->reduced_value = false;
  1654. } else {
  1655. p_binary_op->reduced_value = true;
  1656. }
  1657. } else {
  1658. ERR_PRINT("Parser bug: unknown binary operation.");
  1659. }
  1660. }
  1661. p_binary_op->set_datatype(type_from_variant(p_binary_op->reduced_value, p_binary_op));
  1662. return;
  1663. }
  1664. GDScriptParser::DataType result;
  1665. if (left_type.is_variant() || right_type.is_variant()) {
  1666. // Cannot infer type because one operand can be anything.
  1667. result.kind = GDScriptParser::DataType::VARIANT;
  1668. mark_node_unsafe(p_binary_op);
  1669. } else {
  1670. if (p_binary_op->variant_op < Variant::OP_MAX) {
  1671. bool valid = false;
  1672. result = get_operation_type(p_binary_op->variant_op, left_type, right_type, valid, p_binary_op);
  1673. if (!valid) {
  1674. push_error(vformat(R"(Invalid operands "%s" and "%s" for "%s" operator.)", left_type.to_string(), right_type.to_string(), Variant::get_operator_name(p_binary_op->variant_op)), p_binary_op);
  1675. }
  1676. } else {
  1677. if (p_binary_op->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
  1678. GDScriptParser::DataType test_type = right_type;
  1679. test_type.is_meta_type = false;
  1680. if (!is_type_compatible(test_type, p_binary_op->left_operand->get_datatype(), false)) {
  1681. // Test reverse as well to consider for subtypes.
  1682. if (!is_type_compatible(p_binary_op->left_operand->get_datatype(), test_type, false)) {
  1683. if (p_binary_op->left_operand->get_datatype().is_hard_type()) {
  1684. push_error(vformat(R"(Expression is of type "%s" so it can't be of type "%s".)", p_binary_op->left_operand->get_datatype().to_string(), test_type.to_string()), p_binary_op->left_operand);
  1685. } else {
  1686. // TODO: Warning.
  1687. mark_node_unsafe(p_binary_op);
  1688. }
  1689. }
  1690. }
  1691. // "is" operator is always a boolean anyway.
  1692. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1693. result.kind = GDScriptParser::DataType::BUILTIN;
  1694. result.builtin_type = Variant::BOOL;
  1695. } else {
  1696. ERR_PRINT("Parser bug: unknown binary operation.");
  1697. }
  1698. }
  1699. }
  1700. p_binary_op->set_datatype(result);
  1701. }
  1702. void GDScriptAnalyzer::reduce_call(GDScriptParser::CallNode *p_call, bool is_await) {
  1703. bool all_is_constant = true;
  1704. Map<int, GDScriptParser::ArrayNode *> arrays; // For array literal to potentially type when passing.
  1705. for (int i = 0; i < p_call->arguments.size(); i++) {
  1706. reduce_expression(p_call->arguments[i]);
  1707. if (p_call->arguments[i]->type == GDScriptParser::Node::ARRAY) {
  1708. arrays[i] = static_cast<GDScriptParser::ArrayNode *>(p_call->arguments[i]);
  1709. }
  1710. all_is_constant = all_is_constant && p_call->arguments[i]->is_constant;
  1711. }
  1712. GDScriptParser::Node::Type callee_type = p_call->get_callee_type();
  1713. GDScriptParser::DataType call_type;
  1714. if (!p_call->is_super && callee_type == GDScriptParser::Node::IDENTIFIER) {
  1715. // Call to name directly.
  1716. StringName function_name = p_call->function_name;
  1717. Variant::Type builtin_type = GDScriptParser::get_builtin_type(function_name);
  1718. if (builtin_type < Variant::VARIANT_MAX) {
  1719. // Is a builtin constructor.
  1720. call_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1721. call_type.kind = GDScriptParser::DataType::BUILTIN;
  1722. call_type.builtin_type = builtin_type;
  1723. if (builtin_type == Variant::OBJECT) {
  1724. call_type.kind = GDScriptParser::DataType::NATIVE;
  1725. call_type.native_type = function_name; // "Object".
  1726. }
  1727. bool safe_to_fold = true;
  1728. switch (builtin_type) {
  1729. // Those are stored by reference so not suited for compile-time construction.
  1730. // Because in this case they would be the same reference in all constructed values.
  1731. case Variant::OBJECT:
  1732. case Variant::DICTIONARY:
  1733. case Variant::ARRAY:
  1734. case Variant::PACKED_BYTE_ARRAY:
  1735. case Variant::PACKED_INT32_ARRAY:
  1736. case Variant::PACKED_INT64_ARRAY:
  1737. case Variant::PACKED_FLOAT32_ARRAY:
  1738. case Variant::PACKED_FLOAT64_ARRAY:
  1739. case Variant::PACKED_STRING_ARRAY:
  1740. case Variant::PACKED_VECTOR2_ARRAY:
  1741. case Variant::PACKED_VECTOR3_ARRAY:
  1742. case Variant::PACKED_COLOR_ARRAY:
  1743. safe_to_fold = false;
  1744. break;
  1745. default:
  1746. break;
  1747. }
  1748. if (all_is_constant && safe_to_fold) {
  1749. // Construct here.
  1750. Vector<const Variant *> args;
  1751. for (int i = 0; i < p_call->arguments.size(); i++) {
  1752. args.push_back(&(p_call->arguments[i]->reduced_value));
  1753. }
  1754. Callable::CallError err;
  1755. Variant value;
  1756. Variant::construct(builtin_type, value, (const Variant **)args.ptr(), args.size(), err);
  1757. switch (err.error) {
  1758. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT:
  1759. push_error(vformat(R"(Invalid argument for %s constructor: argument %d should be %s but is %s.)", Variant::get_type_name(builtin_type), err.argument + 1,
  1760. Variant::get_type_name(Variant::Type(err.expected)), p_call->arguments[err.argument]->get_datatype().to_string()),
  1761. p_call->arguments[err.argument]);
  1762. break;
  1763. case Callable::CallError::CALL_ERROR_INVALID_METHOD: {
  1764. String signature = Variant::get_type_name(builtin_type) + "(";
  1765. for (int i = 0; i < p_call->arguments.size(); i++) {
  1766. if (i > 0) {
  1767. signature += ", ";
  1768. }
  1769. signature += p_call->arguments[i]->get_datatype().to_string();
  1770. }
  1771. signature += ")";
  1772. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call->callee);
  1773. } break;
  1774. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  1775. push_error(vformat(R"(Too many arguments for %s constructor. Received %d but expected %d.)", Variant::get_type_name(builtin_type), p_call->arguments.size(), err.expected), p_call);
  1776. break;
  1777. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  1778. push_error(vformat(R"(Too few arguments for %s constructor. Received %d but expected %d.)", Variant::get_type_name(builtin_type), p_call->arguments.size(), err.expected), p_call);
  1779. break;
  1780. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  1781. break; // Can't happen in a builtin constructor.
  1782. case Callable::CallError::CALL_OK:
  1783. p_call->is_constant = true;
  1784. p_call->reduced_value = value;
  1785. break;
  1786. }
  1787. } else {
  1788. // TODO: Check constructors without constants.
  1789. // If there's one argument, try to use copy constructor (those aren't explicitly defined).
  1790. if (p_call->arguments.size() == 1) {
  1791. GDScriptParser::DataType arg_type = p_call->arguments[0]->get_datatype();
  1792. if (arg_type.is_variant()) {
  1793. mark_node_unsafe(p_call->arguments[0]);
  1794. } else {
  1795. if (arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == builtin_type) {
  1796. // Okay.
  1797. p_call->set_datatype(call_type);
  1798. return;
  1799. }
  1800. }
  1801. }
  1802. List<MethodInfo> constructors;
  1803. Variant::get_constructor_list(builtin_type, &constructors);
  1804. bool match = false;
  1805. for (const MethodInfo &info : constructors) {
  1806. if (p_call->arguments.size() < info.arguments.size() - info.default_arguments.size()) {
  1807. continue;
  1808. }
  1809. if (p_call->arguments.size() > info.arguments.size()) {
  1810. continue;
  1811. }
  1812. bool types_match = true;
  1813. for (int i = 0; i < p_call->arguments.size(); i++) {
  1814. GDScriptParser::DataType par_type = type_from_property(info.arguments[i]);
  1815. if (!is_type_compatible(par_type, p_call->arguments[i]->get_datatype(), true)) {
  1816. types_match = false;
  1817. break;
  1818. #ifdef DEBUG_ENABLED
  1819. } else {
  1820. if (par_type.builtin_type == Variant::INT && p_call->arguments[i]->get_datatype().builtin_type == Variant::FLOAT) {
  1821. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  1822. }
  1823. #endif
  1824. }
  1825. }
  1826. if (types_match) {
  1827. match = true;
  1828. call_type = type_from_property(info.return_val);
  1829. break;
  1830. }
  1831. }
  1832. if (!match) {
  1833. String signature = Variant::get_type_name(builtin_type) + "(";
  1834. for (int i = 0; i < p_call->arguments.size(); i++) {
  1835. if (i > 0) {
  1836. signature += ", ";
  1837. }
  1838. signature += p_call->arguments[i]->get_datatype().to_string();
  1839. }
  1840. signature += ")";
  1841. push_error(vformat(R"(No constructor of "%s" matches the signature "%s".)", Variant::get_type_name(builtin_type), signature), p_call);
  1842. }
  1843. }
  1844. p_call->set_datatype(call_type);
  1845. return;
  1846. } else if (GDScriptUtilityFunctions::function_exists(function_name)) {
  1847. MethodInfo function_info = GDScriptUtilityFunctions::get_function_info(function_name);
  1848. if (all_is_constant && GDScriptUtilityFunctions::is_function_constant(function_name)) {
  1849. // Can call on compilation.
  1850. Vector<const Variant *> args;
  1851. for (int i = 0; i < p_call->arguments.size(); i++) {
  1852. args.push_back(&(p_call->arguments[i]->reduced_value));
  1853. }
  1854. Variant value;
  1855. Callable::CallError err;
  1856. GDScriptUtilityFunctions::get_function(function_name)(&value, (const Variant **)args.ptr(), args.size(), err);
  1857. switch (err.error) {
  1858. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
  1859. PropertyInfo wrong_arg = function_info.arguments[err.argument];
  1860. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*", function_name, err.argument + 1,
  1861. type_from_property(wrong_arg).to_string(), p_call->arguments[err.argument]->get_datatype().to_string()),
  1862. p_call->arguments[err.argument]);
  1863. } break;
  1864. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  1865. push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);
  1866. break;
  1867. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  1868. push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
  1869. break;
  1870. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  1871. push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
  1872. break;
  1873. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  1874. break; // Can't happen in a builtin constructor.
  1875. case Callable::CallError::CALL_OK:
  1876. p_call->is_constant = true;
  1877. p_call->reduced_value = value;
  1878. break;
  1879. }
  1880. } else {
  1881. validate_call_arg(function_info, p_call);
  1882. }
  1883. p_call->set_datatype(type_from_property(function_info.return_val));
  1884. return;
  1885. } else if (Variant::has_utility_function(function_name)) {
  1886. MethodInfo function_info = info_from_utility_func(function_name);
  1887. if (all_is_constant && Variant::get_utility_function_type(function_name) == Variant::UTILITY_FUNC_TYPE_MATH) {
  1888. // Can call on compilation.
  1889. Vector<const Variant *> args;
  1890. for (int i = 0; i < p_call->arguments.size(); i++) {
  1891. args.push_back(&(p_call->arguments[i]->reduced_value));
  1892. }
  1893. Variant value;
  1894. Callable::CallError err;
  1895. Variant::call_utility_function(function_name, &value, (const Variant **)args.ptr(), args.size(), err);
  1896. switch (err.error) {
  1897. case Callable::CallError::CALL_ERROR_INVALID_ARGUMENT: {
  1898. PropertyInfo wrong_arg = function_info.arguments[err.argument];
  1899. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*", function_name, err.argument + 1,
  1900. type_from_property(wrong_arg).to_string(), p_call->arguments[err.argument]->get_datatype().to_string()),
  1901. p_call->arguments[err.argument]);
  1902. } break;
  1903. case Callable::CallError::CALL_ERROR_INVALID_METHOD:
  1904. push_error(vformat(R"(Invalid call for function "%s".)", function_name), p_call);
  1905. break;
  1906. case Callable::CallError::CALL_ERROR_TOO_MANY_ARGUMENTS:
  1907. push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
  1908. break;
  1909. case Callable::CallError::CALL_ERROR_TOO_FEW_ARGUMENTS:
  1910. push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", function_name, err.expected, p_call->arguments.size()), p_call);
  1911. break;
  1912. case Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL:
  1913. break; // Can't happen in a builtin constructor.
  1914. case Callable::CallError::CALL_OK:
  1915. p_call->is_constant = true;
  1916. p_call->reduced_value = value;
  1917. break;
  1918. }
  1919. } else {
  1920. validate_call_arg(function_info, p_call);
  1921. }
  1922. p_call->set_datatype(type_from_property(function_info.return_val));
  1923. return;
  1924. }
  1925. }
  1926. GDScriptParser::DataType base_type;
  1927. call_type.kind = GDScriptParser::DataType::VARIANT;
  1928. bool is_self = false;
  1929. if (p_call->is_super) {
  1930. base_type = parser->current_class->base_type;
  1931. base_type.is_meta_type = false;
  1932. is_self = true;
  1933. } else if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  1934. base_type = parser->current_class->get_datatype();
  1935. base_type.is_meta_type = false;
  1936. is_self = true;
  1937. } else if (callee_type == GDScriptParser::Node::SUBSCRIPT) {
  1938. GDScriptParser::SubscriptNode *subscript = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee);
  1939. if (subscript->base == nullptr) {
  1940. // Invalid syntax, error already set on parser.
  1941. p_call->set_datatype(call_type);
  1942. mark_node_unsafe(p_call);
  1943. return;
  1944. }
  1945. if (!subscript->is_attribute) {
  1946. // Invalid call. Error already sent in parser.
  1947. // TODO: Could check if Callable here.
  1948. p_call->set_datatype(call_type);
  1949. mark_node_unsafe(p_call);
  1950. return;
  1951. }
  1952. if (subscript->attribute == nullptr) {
  1953. // Invalid call. Error already sent in parser.
  1954. p_call->set_datatype(call_type);
  1955. mark_node_unsafe(p_call);
  1956. return;
  1957. }
  1958. GDScriptParser::IdentifierNode *base_id = nullptr;
  1959. if (subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  1960. base_id = static_cast<GDScriptParser::IdentifierNode *>(subscript->base);
  1961. }
  1962. if (base_id && GDScriptParser::get_builtin_type(base_id->name) < Variant::VARIANT_MAX) {
  1963. base_type = make_builtin_meta_type(GDScriptParser::get_builtin_type(base_id->name));
  1964. } else {
  1965. reduce_expression(subscript->base);
  1966. base_type = subscript->base->get_datatype();
  1967. }
  1968. } else {
  1969. // Invalid call. Error already sent in parser.
  1970. // TODO: Could check if Callable here too.
  1971. p_call->set_datatype(call_type);
  1972. mark_node_unsafe(p_call);
  1973. return;
  1974. }
  1975. bool is_static = false;
  1976. bool is_vararg = false;
  1977. int default_arg_count = 0;
  1978. GDScriptParser::DataType return_type;
  1979. List<GDScriptParser::DataType> par_types;
  1980. if (get_function_signature(p_call, base_type, p_call->function_name, return_type, par_types, default_arg_count, is_static, is_vararg)) {
  1981. // If the function require typed arrays we must make literals be typed.
  1982. for (Map<int, GDScriptParser::ArrayNode *>::Element *E = arrays.front(); E; E = E->next()) {
  1983. int index = E->key();
  1984. if (index < par_types.size() && par_types[index].has_container_element_type()) {
  1985. update_array_literal_element_type(par_types[index], E->get());
  1986. }
  1987. }
  1988. validate_call_arg(par_types, default_arg_count, is_vararg, p_call);
  1989. if (is_self && parser->current_function != nullptr && parser->current_function->is_static && !is_static) {
  1990. push_error(vformat(R"*(Cannot call non-static function "%s()" from static function "%s()".)*", p_call->function_name, parser->current_function->identifier->name), p_call->callee);
  1991. } else if (!is_self && base_type.is_meta_type && !is_static) {
  1992. base_type.is_meta_type = false; // For `to_string()`.
  1993. push_error(vformat(R"*(Cannot call non-static function "%s()" on the class "%s" directly. Make an instance instead.)*", p_call->function_name, base_type.to_string()), p_call->callee);
  1994. } else if (is_self && !is_static && !lambda_stack.is_empty()) {
  1995. push_error(vformat(R"*(Cannot call non-static function "%s()" from a lambda function.)*", p_call->function_name), p_call->callee);
  1996. }
  1997. call_type = return_type;
  1998. } else {
  1999. // Check if the name exists as something else.
  2000. bool found = false;
  2001. if (!p_call->is_super && callee_type != GDScriptParser::Node::NONE) {
  2002. GDScriptParser::IdentifierNode *callee_id;
  2003. if (callee_type == GDScriptParser::Node::IDENTIFIER) {
  2004. callee_id = static_cast<GDScriptParser::IdentifierNode *>(p_call->callee);
  2005. } else {
  2006. // Can only be attribute.
  2007. callee_id = static_cast<GDScriptParser::SubscriptNode *>(p_call->callee)->attribute;
  2008. }
  2009. if (callee_id) {
  2010. reduce_identifier_from_base(callee_id, &base_type);
  2011. GDScriptParser::DataType callee_datatype = callee_id->get_datatype();
  2012. if (callee_datatype.is_set() && !callee_datatype.is_variant()) {
  2013. found = true;
  2014. if (callee_datatype.builtin_type == Variant::CALLABLE) {
  2015. push_error(vformat(R"*(Name "%s" is a Callable. You can call it with "%s.call()" instead.)*", p_call->function_name, p_call->function_name), p_call->callee);
  2016. } else {
  2017. push_error(vformat(R"*(Name "%s" called as a function but is a "%s".)*", p_call->function_name, callee_datatype.to_string()), p_call->callee);
  2018. }
  2019. #ifdef DEBUG_ENABLED
  2020. } else if (!is_self && !(base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN)) {
  2021. parser->push_warning(p_call, GDScriptWarning::UNSAFE_METHOD_ACCESS, p_call->function_name, base_type.to_string());
  2022. mark_node_unsafe(p_call);
  2023. #endif
  2024. }
  2025. }
  2026. }
  2027. if (!found && (is_self || (base_type.is_hard_type() && base_type.kind == GDScriptParser::DataType::BUILTIN))) {
  2028. String base_name = is_self && !p_call->is_super ? "self" : base_type.to_string();
  2029. push_error(vformat(R"*(Function "%s()" not found in base %s.)*", p_call->function_name, base_name), p_call->is_super ? p_call : p_call->callee);
  2030. }
  2031. }
  2032. if (call_type.is_coroutine && !is_await) {
  2033. push_error(vformat(R"*(Function "%s()" is a coroutine, so it must be called with "await".)*", p_call->function_name), p_call->callee);
  2034. }
  2035. p_call->set_datatype(call_type);
  2036. }
  2037. void GDScriptAnalyzer::reduce_cast(GDScriptParser::CastNode *p_cast) {
  2038. reduce_expression(p_cast->operand);
  2039. GDScriptParser::DataType cast_type = resolve_datatype(p_cast->cast_type);
  2040. if (!cast_type.is_set()) {
  2041. return;
  2042. }
  2043. cast_type.is_meta_type = false; // The casted value won't be a type name.
  2044. p_cast->set_datatype(cast_type);
  2045. if (!cast_type.is_variant()) {
  2046. GDScriptParser::DataType op_type = p_cast->operand->get_datatype();
  2047. if (!op_type.is_variant()) {
  2048. bool valid = false;
  2049. if (op_type.kind == GDScriptParser::DataType::BUILTIN && cast_type.kind == GDScriptParser::DataType::BUILTIN) {
  2050. valid = Variant::can_convert(op_type.builtin_type, cast_type.builtin_type);
  2051. } else if (op_type.kind != GDScriptParser::DataType::BUILTIN && cast_type.kind != GDScriptParser::DataType::BUILTIN) {
  2052. valid = is_type_compatible(cast_type, op_type) || is_type_compatible(op_type, cast_type);
  2053. }
  2054. if (!valid) {
  2055. push_error(vformat(R"(Invalid cast. Cannot convert from "%s" to "%s".)", op_type.to_string(), cast_type.to_string()), p_cast->cast_type);
  2056. }
  2057. }
  2058. } else {
  2059. mark_node_unsafe(p_cast);
  2060. }
  2061. #ifdef DEBUG_ENABLED
  2062. if (p_cast->operand->get_datatype().is_variant()) {
  2063. parser->push_warning(p_cast, GDScriptWarning::UNSAFE_CAST, cast_type.to_string());
  2064. mark_node_unsafe(p_cast);
  2065. }
  2066. #endif
  2067. // TODO: Perform cast on constants.
  2068. }
  2069. void GDScriptAnalyzer::reduce_dictionary(GDScriptParser::DictionaryNode *p_dictionary) {
  2070. HashMap<Variant, GDScriptParser::ExpressionNode *, VariantHasher, VariantComparator> elements;
  2071. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  2072. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  2073. if (p_dictionary->style == GDScriptParser::DictionaryNode::PYTHON_DICT) {
  2074. reduce_expression(element.key);
  2075. }
  2076. reduce_expression(element.value);
  2077. if (element.key->is_constant) {
  2078. if (elements.has(element.key->reduced_value)) {
  2079. push_error(vformat(R"(Key "%s" was already used in this dictionary (at line %d).)", element.key->reduced_value, elements[element.key->reduced_value]->start_line), element.key);
  2080. } else {
  2081. elements[element.key->reduced_value] = element.value;
  2082. }
  2083. }
  2084. }
  2085. // It's dictionary in any case.
  2086. GDScriptParser::DataType dict_type;
  2087. dict_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2088. dict_type.kind = GDScriptParser::DataType::BUILTIN;
  2089. dict_type.builtin_type = Variant::DICTIONARY;
  2090. dict_type.is_constant = true;
  2091. p_dictionary->set_datatype(dict_type);
  2092. }
  2093. void GDScriptAnalyzer::reduce_get_node(GDScriptParser::GetNodeNode *p_get_node) {
  2094. GDScriptParser::DataType result;
  2095. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2096. result.kind = GDScriptParser::DataType::NATIVE;
  2097. result.native_type = "Node";
  2098. result.builtin_type = Variant::OBJECT;
  2099. if (!ClassDB::is_parent_class(parser->current_class->base_type.native_type, result.native_type)) {
  2100. push_error(R"*(Cannot use shorthand "get_node()" notation ("$") on a class that isn't a node.)*", p_get_node);
  2101. } else if (!lambda_stack.is_empty()) {
  2102. push_error(R"*(Cannot use shorthand "get_node()" notation ("$") inside a lambda. Use a captured variable instead.)*", p_get_node);
  2103. }
  2104. p_get_node->set_datatype(result);
  2105. }
  2106. GDScriptParser::DataType GDScriptAnalyzer::make_global_class_meta_type(const StringName &p_class_name, const GDScriptParser::Node *p_source) {
  2107. Ref<GDScriptParserRef> ref = get_parser_for(ScriptServer::get_global_class_path(p_class_name));
  2108. Error err = ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
  2109. if (err) {
  2110. push_error(vformat(R"(Could not resolve class "%s", because of a parser error.)", p_class_name), p_source);
  2111. GDScriptParser::DataType type;
  2112. type.type_source = GDScriptParser::DataType::UNDETECTED;
  2113. type.kind = GDScriptParser::DataType::VARIANT;
  2114. return type;
  2115. }
  2116. GDScriptParser::DataType type;
  2117. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2118. type.kind = GDScriptParser::DataType::CLASS;
  2119. type.builtin_type = Variant::OBJECT;
  2120. type.native_type = ScriptServer::get_global_class_native_base(p_class_name);
  2121. type.class_type = ref->get_parser()->head;
  2122. type.script_path = ref->get_parser()->script_path;
  2123. type.is_constant = true;
  2124. type.is_meta_type = true;
  2125. return type;
  2126. }
  2127. void GDScriptAnalyzer::reduce_identifier_from_base(GDScriptParser::IdentifierNode *p_identifier, GDScriptParser::DataType *p_base) {
  2128. GDScriptParser::DataType base;
  2129. if (p_base == nullptr) {
  2130. base = type_from_metatype(parser->current_class->get_datatype());
  2131. } else {
  2132. base = *p_base;
  2133. }
  2134. const StringName &name = p_identifier->name;
  2135. if (base.kind == GDScriptParser::DataType::BUILTIN) {
  2136. if (base.is_meta_type) {
  2137. bool valid = true;
  2138. Variant result = Variant::get_constant_value(base.builtin_type, name, &valid);
  2139. if (valid) {
  2140. p_identifier->is_constant = true;
  2141. p_identifier->reduced_value = result;
  2142. p_identifier->set_datatype(type_from_variant(result, p_identifier));
  2143. } else {
  2144. push_error(vformat(R"(Cannot find constant "%s" on type "%s".)", name, base.to_string()), p_identifier);
  2145. }
  2146. } else {
  2147. switch (base.builtin_type) {
  2148. case Variant::NIL: {
  2149. push_error(vformat(R"(Invalid get index "%s" on base Nil)", name), p_identifier);
  2150. return;
  2151. }
  2152. case Variant::DICTIONARY: {
  2153. GDScriptParser::DataType dummy;
  2154. dummy.kind = GDScriptParser::DataType::VARIANT;
  2155. p_identifier->set_datatype(dummy);
  2156. return;
  2157. }
  2158. default: {
  2159. Callable::CallError temp;
  2160. Variant dummy;
  2161. Variant::construct(base.builtin_type, dummy, nullptr, 0, temp);
  2162. List<PropertyInfo> properties;
  2163. dummy.get_property_list(&properties);
  2164. for (const PropertyInfo &prop : properties) {
  2165. if (prop.name == name) {
  2166. p_identifier->set_datatype(type_from_property(prop));
  2167. return;
  2168. }
  2169. }
  2170. push_error(vformat(R"(Cannot find property "%s" on base "%s".)", name, base.to_string()), p_identifier);
  2171. }
  2172. }
  2173. }
  2174. return;
  2175. }
  2176. if (base.kind == GDScriptParser::DataType::ENUM) {
  2177. if (base.is_meta_type) {
  2178. if (base.enum_values.has(name)) {
  2179. p_identifier->is_constant = true;
  2180. p_identifier->reduced_value = base.enum_values[name];
  2181. GDScriptParser::DataType result;
  2182. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2183. result.kind = GDScriptParser::DataType::ENUM_VALUE;
  2184. result.builtin_type = base.builtin_type;
  2185. result.native_type = base.native_type;
  2186. result.enum_type = name;
  2187. p_identifier->set_datatype(result);
  2188. } else {
  2189. push_error(vformat(R"(Cannot find value "%s" in "%s".)", name, base.to_string()), p_identifier);
  2190. }
  2191. } else {
  2192. push_error(R"(Cannot get property from enum value.)", p_identifier);
  2193. }
  2194. return;
  2195. }
  2196. GDScriptParser::ClassNode *base_class = base.class_type;
  2197. // TODO: Switch current class/function/suite here to avoid misrepresenting identifiers (in recursive reduce calls).
  2198. while (base_class != nullptr) {
  2199. if (base_class->identifier && base_class->identifier->name == name) {
  2200. p_identifier->set_datatype(base_class->get_datatype());
  2201. return;
  2202. }
  2203. if (base_class->has_member(name)) {
  2204. const GDScriptParser::ClassNode::Member &member = base_class->get_member(name);
  2205. p_identifier->set_datatype(member.get_datatype());
  2206. switch (member.type) {
  2207. case GDScriptParser::ClassNode::Member::CONSTANT:
  2208. // For out-of-order resolution:
  2209. reduce_expression(member.constant->initializer);
  2210. p_identifier->is_constant = true;
  2211. p_identifier->reduced_value = member.constant->initializer->reduced_value;
  2212. p_identifier->set_datatype(member.constant->initializer->get_datatype());
  2213. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  2214. p_identifier->constant_source = member.constant;
  2215. break;
  2216. case GDScriptParser::ClassNode::Member::ENUM_VALUE:
  2217. p_identifier->is_constant = true;
  2218. p_identifier->reduced_value = member.enum_value.value;
  2219. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_CONSTANT;
  2220. break;
  2221. case GDScriptParser::ClassNode::Member::VARIABLE:
  2222. p_identifier->source = GDScriptParser::IdentifierNode::MEMBER_VARIABLE;
  2223. p_identifier->variable_source = member.variable;
  2224. member.variable->usages += 1;
  2225. break;
  2226. case GDScriptParser::ClassNode::Member::FUNCTION:
  2227. resolve_function_signature(member.function);
  2228. p_identifier->set_datatype(make_callable_type(member.function->info));
  2229. break;
  2230. case GDScriptParser::ClassNode::Member::CLASS:
  2231. // For out-of-order resolution:
  2232. resolve_class_interface(member.m_class);
  2233. p_identifier->set_datatype(member.m_class->get_datatype());
  2234. break;
  2235. default:
  2236. break; // Type already set.
  2237. }
  2238. return;
  2239. }
  2240. // Check outer constants.
  2241. // TODO: Allow outer static functions.
  2242. GDScriptParser::ClassNode *outer = base_class->outer;
  2243. while (outer != nullptr) {
  2244. if (outer->has_member(name)) {
  2245. const GDScriptParser::ClassNode::Member &member = outer->get_member(name);
  2246. switch (member.type) {
  2247. case GDScriptParser::ClassNode::Member::CONSTANT: {
  2248. // TODO: Make sure loops won't cause problem. And make special error message for those.
  2249. // For out-of-order resolution:
  2250. reduce_expression(member.constant->initializer);
  2251. p_identifier->set_datatype(member.get_datatype());
  2252. p_identifier->is_constant = true;
  2253. p_identifier->reduced_value = member.constant->initializer->reduced_value;
  2254. return;
  2255. } break;
  2256. case GDScriptParser::ClassNode::Member::ENUM_VALUE: {
  2257. p_identifier->set_datatype(member.get_datatype());
  2258. p_identifier->is_constant = true;
  2259. p_identifier->reduced_value = member.enum_value.value;
  2260. return;
  2261. } break;
  2262. case GDScriptParser::ClassNode::Member::ENUM: {
  2263. p_identifier->set_datatype(member.get_datatype());
  2264. p_identifier->is_constant = false;
  2265. return;
  2266. } break;
  2267. default:
  2268. break;
  2269. }
  2270. }
  2271. outer = outer->outer;
  2272. }
  2273. base_class = base_class->base_type.class_type;
  2274. }
  2275. // Check native members.
  2276. const StringName &native = base.native_type;
  2277. if (class_exists(native)) {
  2278. PropertyInfo prop_info;
  2279. MethodInfo method_info;
  2280. if (ClassDB::get_property_info(native, name, &prop_info)) {
  2281. p_identifier->set_datatype(type_from_property(prop_info));
  2282. return;
  2283. }
  2284. if (ClassDB::get_method_info(native, name, &method_info)) {
  2285. // Method is callable.
  2286. p_identifier->set_datatype(make_callable_type(method_info));
  2287. return;
  2288. }
  2289. if (ClassDB::get_signal(native, name, &method_info)) {
  2290. // Signal is a type too.
  2291. p_identifier->set_datatype(make_signal_type(method_info));
  2292. return;
  2293. }
  2294. if (ClassDB::has_enum(native, name)) {
  2295. p_identifier->set_datatype(make_native_enum_type(native, name));
  2296. return;
  2297. }
  2298. bool valid = false;
  2299. int int_constant = ClassDB::get_integer_constant(native, name, &valid);
  2300. if (valid) {
  2301. p_identifier->is_constant = true;
  2302. p_identifier->reduced_value = int_constant;
  2303. p_identifier->set_datatype(type_from_variant(int_constant, p_identifier));
  2304. return;
  2305. }
  2306. }
  2307. }
  2308. void GDScriptAnalyzer::reduce_identifier(GDScriptParser::IdentifierNode *p_identifier, bool can_be_builtin) {
  2309. // TODO: This is opportunity to further infer types.
  2310. // Check if we are inside and enum. This allows enum values to access other elements of the same enum.
  2311. if (current_enum) {
  2312. for (int i = 0; i < current_enum->values.size(); i++) {
  2313. const GDScriptParser::EnumNode::Value &element = current_enum->values[i];
  2314. if (element.identifier->name == p_identifier->name) {
  2315. GDScriptParser::DataType type;
  2316. type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2317. type.kind = element.parent_enum->identifier ? GDScriptParser::DataType::ENUM_VALUE : GDScriptParser::DataType::BUILTIN;
  2318. type.builtin_type = Variant::INT;
  2319. type.is_constant = true;
  2320. if (element.parent_enum->identifier) {
  2321. type.enum_type = element.parent_enum->identifier->name;
  2322. }
  2323. p_identifier->set_datatype(type);
  2324. if (element.resolved) {
  2325. p_identifier->is_constant = true;
  2326. p_identifier->reduced_value = element.value;
  2327. } else {
  2328. push_error(R"(Cannot use another enum element before it was declared.)", p_identifier);
  2329. }
  2330. return; // Found anyway.
  2331. }
  2332. }
  2333. }
  2334. bool found_source = false;
  2335. // Check if identifier is local.
  2336. // If that's the case, the declaration already was solved before.
  2337. switch (p_identifier->source) {
  2338. case GDScriptParser::IdentifierNode::FUNCTION_PARAMETER:
  2339. p_identifier->set_datatype(p_identifier->parameter_source->get_datatype());
  2340. found_source = true;
  2341. break;
  2342. case GDScriptParser::IdentifierNode::LOCAL_CONSTANT:
  2343. case GDScriptParser::IdentifierNode::MEMBER_CONSTANT:
  2344. p_identifier->set_datatype(p_identifier->constant_source->get_datatype());
  2345. p_identifier->is_constant = true;
  2346. // TODO: Constant should have a value on the node itself.
  2347. p_identifier->reduced_value = p_identifier->constant_source->initializer->reduced_value;
  2348. found_source = true;
  2349. break;
  2350. case GDScriptParser::IdentifierNode::MEMBER_VARIABLE:
  2351. p_identifier->variable_source->usages++;
  2352. [[fallthrough]];
  2353. case GDScriptParser::IdentifierNode::LOCAL_VARIABLE:
  2354. p_identifier->set_datatype(p_identifier->variable_source->get_datatype());
  2355. found_source = true;
  2356. break;
  2357. case GDScriptParser::IdentifierNode::LOCAL_ITERATOR:
  2358. p_identifier->set_datatype(p_identifier->bind_source->get_datatype());
  2359. found_source = true;
  2360. break;
  2361. case GDScriptParser::IdentifierNode::LOCAL_BIND: {
  2362. GDScriptParser::DataType result = p_identifier->bind_source->get_datatype();
  2363. result.is_constant = true;
  2364. p_identifier->set_datatype(result);
  2365. found_source = true;
  2366. } break;
  2367. case GDScriptParser::IdentifierNode::UNDEFINED_SOURCE:
  2368. break;
  2369. }
  2370. // Not a local, so check members.
  2371. if (!found_source) {
  2372. reduce_identifier_from_base(p_identifier);
  2373. if (p_identifier->source != GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->get_datatype().is_set()) {
  2374. // Found.
  2375. found_source = true;
  2376. }
  2377. }
  2378. if (found_source) {
  2379. // If the identifier is local, check if it's any kind of capture by comparing their source function.
  2380. // Only capture locals and members and enum values. Constants are still accessible from the lambda using the script reference.
  2381. if (p_identifier->source == GDScriptParser::IdentifierNode::UNDEFINED_SOURCE || p_identifier->source == GDScriptParser::IdentifierNode::MEMBER_CONSTANT || lambda_stack.is_empty()) {
  2382. return;
  2383. }
  2384. GDScriptParser::FunctionNode *function_test = lambda_stack.back()->get()->function;
  2385. while (function_test != nullptr && function_test != p_identifier->source_function && function_test->source_lambda != nullptr && !function_test->source_lambda->captures_indices.has(p_identifier->name)) {
  2386. function_test->source_lambda->captures_indices[p_identifier->name] = function_test->source_lambda->captures.size();
  2387. function_test->source_lambda->captures.push_back(p_identifier);
  2388. function_test = function_test->source_lambda->parent_function;
  2389. }
  2390. return;
  2391. }
  2392. StringName name = p_identifier->name;
  2393. p_identifier->source = GDScriptParser::IdentifierNode::UNDEFINED_SOURCE;
  2394. // Check globals. We make an exception for Variant::OBJECT because it's the base class for
  2395. // non-builtin types so we allow doing e.g. Object.new()
  2396. Variant::Type builtin_type = GDScriptParser::get_builtin_type(name);
  2397. if (builtin_type != Variant::OBJECT && builtin_type < Variant::VARIANT_MAX) {
  2398. if (can_be_builtin) {
  2399. p_identifier->set_datatype(make_builtin_meta_type(builtin_type));
  2400. return;
  2401. } else {
  2402. push_error(R"(Builtin type cannot be used as a name on its own.)", p_identifier);
  2403. }
  2404. }
  2405. if (class_exists(name)) {
  2406. p_identifier->set_datatype(make_native_meta_type(name));
  2407. return;
  2408. }
  2409. if (ScriptServer::is_global_class(name)) {
  2410. p_identifier->set_datatype(make_global_class_meta_type(name, p_identifier));
  2411. return;
  2412. }
  2413. // Try singletons.
  2414. // Do this before globals because this might be a singleton loading another one before it's compiled.
  2415. if (ProjectSettings::get_singleton()->has_autoload(name)) {
  2416. const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(name);
  2417. if (autoload.is_singleton) {
  2418. // Singleton exists, so it's at least a Node.
  2419. GDScriptParser::DataType result;
  2420. result.kind = GDScriptParser::DataType::NATIVE;
  2421. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2422. if (autoload.path.to_lower().ends_with(GDScriptLanguage::get_singleton()->get_extension())) {
  2423. Ref<GDScriptParserRef> parser = get_parser_for(autoload.path);
  2424. if (parser.is_valid()) {
  2425. Error err = parser->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
  2426. if (err == OK) {
  2427. result = type_from_metatype(parser->get_parser()->head->get_datatype());
  2428. }
  2429. }
  2430. }
  2431. result.is_constant = true;
  2432. p_identifier->set_datatype(result);
  2433. return;
  2434. }
  2435. }
  2436. if (GDScriptLanguage::get_singleton()->get_global_map().has(name)) {
  2437. int idx = GDScriptLanguage::get_singleton()->get_global_map()[name];
  2438. Variant constant = GDScriptLanguage::get_singleton()->get_global_array()[idx];
  2439. p_identifier->set_datatype(type_from_variant(constant, p_identifier));
  2440. p_identifier->is_constant = true;
  2441. p_identifier->reduced_value = constant;
  2442. return;
  2443. }
  2444. if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(name)) {
  2445. Variant constant = GDScriptLanguage::get_singleton()->get_named_globals_map()[name];
  2446. p_identifier->set_datatype(type_from_variant(constant, p_identifier));
  2447. p_identifier->is_constant = true;
  2448. p_identifier->reduced_value = constant;
  2449. return;
  2450. }
  2451. // Not found.
  2452. // Check if it's a builtin function.
  2453. if (GDScriptUtilityFunctions::function_exists(name)) {
  2454. push_error(vformat(R"(Built-in function "%s" cannot be used as an identifier.)", name), p_identifier);
  2455. } else {
  2456. push_error(vformat(R"(Identifier "%s" not declared in the current scope.)", name), p_identifier);
  2457. }
  2458. GDScriptParser::DataType dummy;
  2459. dummy.kind = GDScriptParser::DataType::VARIANT;
  2460. p_identifier->set_datatype(dummy); // Just so type is set to something.
  2461. }
  2462. void GDScriptAnalyzer::reduce_lambda(GDScriptParser::LambdaNode *p_lambda) {
  2463. // Lambda is always a Callable.
  2464. GDScriptParser::DataType lambda_type;
  2465. lambda_type.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  2466. lambda_type.kind = GDScriptParser::DataType::BUILTIN;
  2467. lambda_type.builtin_type = Variant::CALLABLE;
  2468. p_lambda->set_datatype(lambda_type);
  2469. if (p_lambda->function == nullptr) {
  2470. return;
  2471. }
  2472. GDScriptParser::FunctionNode *previous_function = parser->current_function;
  2473. parser->current_function = p_lambda->function;
  2474. lambda_stack.push_back(p_lambda);
  2475. for (int i = 0; i < p_lambda->function->parameters.size(); i++) {
  2476. resolve_parameter(p_lambda->function->parameters[i]);
  2477. }
  2478. resolve_suite(p_lambda->function->body);
  2479. int captures_amount = p_lambda->captures.size();
  2480. if (captures_amount > 0) {
  2481. // Create space for lambda parameters.
  2482. // At the beginning to not mess with optional parameters.
  2483. int param_count = p_lambda->function->parameters.size();
  2484. p_lambda->function->parameters.resize(param_count + captures_amount);
  2485. for (int i = param_count - 1; i >= 0; i--) {
  2486. p_lambda->function->parameters.write[i + captures_amount] = p_lambda->function->parameters[i];
  2487. p_lambda->function->parameters_indices[p_lambda->function->parameters[i]->identifier->name] = i + captures_amount;
  2488. }
  2489. // Add captures as extra parameters at the beginning.
  2490. for (int i = 0; i < p_lambda->captures.size(); i++) {
  2491. GDScriptParser::IdentifierNode *capture = p_lambda->captures[i];
  2492. GDScriptParser::ParameterNode *capture_param = parser->alloc_node<GDScriptParser::ParameterNode>();
  2493. capture_param->identifier = capture;
  2494. capture_param->usages = capture->usages;
  2495. capture_param->set_datatype(capture->get_datatype());
  2496. p_lambda->function->parameters.write[i] = capture_param;
  2497. p_lambda->function->parameters_indices[capture->name] = i;
  2498. }
  2499. }
  2500. lambda_stack.pop_back();
  2501. parser->current_function = previous_function;
  2502. }
  2503. void GDScriptAnalyzer::reduce_literal(GDScriptParser::LiteralNode *p_literal) {
  2504. p_literal->reduced_value = p_literal->value;
  2505. p_literal->is_constant = true;
  2506. p_literal->set_datatype(type_from_variant(p_literal->reduced_value, p_literal));
  2507. }
  2508. void GDScriptAnalyzer::reduce_preload(GDScriptParser::PreloadNode *p_preload) {
  2509. if (!p_preload->path) {
  2510. return;
  2511. }
  2512. reduce_expression(p_preload->path);
  2513. if (!p_preload->path->is_constant) {
  2514. push_error("Preloaded path must be a constant string.", p_preload->path);
  2515. return;
  2516. }
  2517. if (p_preload->path->reduced_value.get_type() != Variant::STRING) {
  2518. push_error("Preloaded path must be a constant string.", p_preload->path);
  2519. } else {
  2520. p_preload->resolved_path = p_preload->path->reduced_value;
  2521. // TODO: Save this as script dependency.
  2522. if (p_preload->resolved_path.is_relative_path()) {
  2523. p_preload->resolved_path = parser->script_path.get_base_dir().plus_file(p_preload->resolved_path);
  2524. }
  2525. p_preload->resolved_path = p_preload->resolved_path.simplify_path();
  2526. if (!FileAccess::exists(p_preload->resolved_path)) {
  2527. push_error(vformat(R"(Preload file "%s" does not exist.)", p_preload->resolved_path), p_preload->path);
  2528. } else {
  2529. // TODO: Don't load if validating: use completion cache.
  2530. p_preload->resource = ResourceLoader::load(p_preload->resolved_path);
  2531. if (p_preload->resource.is_null()) {
  2532. push_error(vformat(R"(Could not p_preload resource file "%s".)", p_preload->resolved_path), p_preload->path);
  2533. }
  2534. }
  2535. }
  2536. p_preload->is_constant = true;
  2537. p_preload->reduced_value = p_preload->resource;
  2538. p_preload->set_datatype(type_from_variant(p_preload->reduced_value, p_preload));
  2539. }
  2540. void GDScriptAnalyzer::reduce_self(GDScriptParser::SelfNode *p_self) {
  2541. p_self->is_constant = false;
  2542. p_self->set_datatype(type_from_metatype(parser->current_class->get_datatype()));
  2543. }
  2544. void GDScriptAnalyzer::reduce_subscript(GDScriptParser::SubscriptNode *p_subscript) {
  2545. if (p_subscript->base == nullptr) {
  2546. return;
  2547. }
  2548. if (p_subscript->base->type == GDScriptParser::Node::IDENTIFIER) {
  2549. reduce_identifier(static_cast<GDScriptParser::IdentifierNode *>(p_subscript->base), true);
  2550. } else {
  2551. reduce_expression(p_subscript->base);
  2552. }
  2553. GDScriptParser::DataType result_type;
  2554. if (p_subscript->is_attribute) {
  2555. if (p_subscript->attribute == nullptr) {
  2556. return;
  2557. }
  2558. if (p_subscript->base->is_constant) {
  2559. // Just try to get it.
  2560. bool valid = false;
  2561. Variant value = p_subscript->base->reduced_value.get_named(p_subscript->attribute->name, valid);
  2562. if (!valid) {
  2563. push_error(vformat(R"(Cannot get member "%s" from "%s".)", p_subscript->attribute->name, p_subscript->base->reduced_value), p_subscript->index);
  2564. } else {
  2565. p_subscript->is_constant = true;
  2566. p_subscript->reduced_value = value;
  2567. result_type = type_from_variant(value, p_subscript);
  2568. }
  2569. result_type.kind = GDScriptParser::DataType::VARIANT;
  2570. } else {
  2571. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  2572. if (base_type.is_variant()) {
  2573. result_type.kind = GDScriptParser::DataType::VARIANT;
  2574. mark_node_unsafe(p_subscript);
  2575. } else {
  2576. reduce_identifier_from_base(p_subscript->attribute, &base_type);
  2577. GDScriptParser::DataType attr_type = p_subscript->attribute->get_datatype();
  2578. if (attr_type.is_set()) {
  2579. result_type = attr_type;
  2580. p_subscript->is_constant = p_subscript->attribute->is_constant;
  2581. p_subscript->reduced_value = p_subscript->attribute->reduced_value;
  2582. } else {
  2583. if (base_type.kind == GDScriptParser::DataType::BUILTIN) {
  2584. push_error(vformat(R"(Cannot find member "%s" in base "%s".)", p_subscript->attribute->name, base_type.to_string()), p_subscript->attribute);
  2585. #ifdef DEBUG_ENABLED
  2586. } else {
  2587. parser->push_warning(p_subscript, GDScriptWarning::UNSAFE_PROPERTY_ACCESS, p_subscript->attribute->name, base_type.to_string());
  2588. #endif
  2589. }
  2590. result_type.kind = GDScriptParser::DataType::VARIANT;
  2591. }
  2592. }
  2593. }
  2594. } else {
  2595. if (p_subscript->index == nullptr) {
  2596. return;
  2597. }
  2598. reduce_expression(p_subscript->index);
  2599. if (p_subscript->base->is_constant && p_subscript->index->is_constant) {
  2600. // Just try to get it.
  2601. bool valid = false;
  2602. Variant value = p_subscript->base->reduced_value.get(p_subscript->index->reduced_value, &valid);
  2603. if (!valid) {
  2604. push_error(vformat(R"(Cannot get index "%s" from "%s".)", p_subscript->index->reduced_value, p_subscript->base->reduced_value), p_subscript->index);
  2605. } else {
  2606. p_subscript->is_constant = true;
  2607. p_subscript->reduced_value = value;
  2608. result_type = type_from_variant(value, p_subscript);
  2609. }
  2610. result_type.kind = GDScriptParser::DataType::VARIANT;
  2611. } else {
  2612. GDScriptParser::DataType base_type = p_subscript->base->get_datatype();
  2613. GDScriptParser::DataType index_type = p_subscript->index->get_datatype();
  2614. if (base_type.is_variant()) {
  2615. result_type.kind = GDScriptParser::DataType::VARIANT;
  2616. mark_node_unsafe(p_subscript);
  2617. } else {
  2618. if (base_type.kind == GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  2619. // Check if indexing is valid.
  2620. bool error = index_type.kind != GDScriptParser::DataType::BUILTIN && base_type.builtin_type != Variant::DICTIONARY;
  2621. if (!error) {
  2622. switch (base_type.builtin_type) {
  2623. // Expect int or real as index.
  2624. case Variant::PACKED_BYTE_ARRAY:
  2625. case Variant::PACKED_COLOR_ARRAY:
  2626. case Variant::PACKED_FLOAT32_ARRAY:
  2627. case Variant::PACKED_FLOAT64_ARRAY:
  2628. case Variant::PACKED_INT32_ARRAY:
  2629. case Variant::PACKED_INT64_ARRAY:
  2630. case Variant::PACKED_STRING_ARRAY:
  2631. case Variant::PACKED_VECTOR2_ARRAY:
  2632. case Variant::PACKED_VECTOR3_ARRAY:
  2633. case Variant::ARRAY:
  2634. case Variant::STRING:
  2635. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT;
  2636. break;
  2637. // Expect String only.
  2638. case Variant::RECT2:
  2639. case Variant::RECT2I:
  2640. case Variant::PLANE:
  2641. case Variant::QUATERNION:
  2642. case Variant::AABB:
  2643. case Variant::OBJECT:
  2644. error = index_type.builtin_type != Variant::STRING;
  2645. break;
  2646. // Expect String or number.
  2647. case Variant::BASIS:
  2648. case Variant::VECTOR2:
  2649. case Variant::VECTOR2I:
  2650. case Variant::VECTOR3:
  2651. case Variant::VECTOR3I:
  2652. case Variant::TRANSFORM2D:
  2653. case Variant::TRANSFORM3D:
  2654. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::FLOAT &&
  2655. index_type.builtin_type != Variant::STRING;
  2656. break;
  2657. // Expect String or int.
  2658. case Variant::COLOR:
  2659. error = index_type.builtin_type != Variant::INT && index_type.builtin_type != Variant::STRING;
  2660. break;
  2661. // Don't support indexing, but we will check it later.
  2662. case Variant::RID:
  2663. case Variant::BOOL:
  2664. case Variant::CALLABLE:
  2665. case Variant::FLOAT:
  2666. case Variant::INT:
  2667. case Variant::NIL:
  2668. case Variant::NODE_PATH:
  2669. case Variant::SIGNAL:
  2670. case Variant::STRING_NAME:
  2671. break;
  2672. // Here for completeness.
  2673. case Variant::DICTIONARY:
  2674. case Variant::VARIANT_MAX:
  2675. break;
  2676. }
  2677. if (error) {
  2678. push_error(vformat(R"(Invalid index type "%s" for a base of type "%s".)", index_type.to_string(), base_type.to_string()), p_subscript->index);
  2679. }
  2680. }
  2681. } else if (base_type.kind != GDScriptParser::DataType::BUILTIN && !index_type.is_variant()) {
  2682. if (index_type.builtin_type != Variant::STRING && index_type.builtin_type != Variant::STRING_NAME) {
  2683. push_error(vformat(R"(Only String or StringName can be used as index for type "%s", but received a "%s".)", base_type.to_string(), index_type.to_string()), p_subscript->index);
  2684. }
  2685. }
  2686. // Check resulting type if possible.
  2687. result_type.builtin_type = Variant::NIL;
  2688. result_type.kind = GDScriptParser::DataType::BUILTIN;
  2689. result_type.type_source = base_type.is_hard_type() ? GDScriptParser::DataType::ANNOTATED_INFERRED : GDScriptParser::DataType::INFERRED;
  2690. switch (base_type.builtin_type) {
  2691. // Can't index at all.
  2692. case Variant::RID:
  2693. case Variant::BOOL:
  2694. case Variant::CALLABLE:
  2695. case Variant::FLOAT:
  2696. case Variant::INT:
  2697. case Variant::NIL:
  2698. case Variant::NODE_PATH:
  2699. case Variant::SIGNAL:
  2700. case Variant::STRING_NAME:
  2701. result_type.kind = GDScriptParser::DataType::VARIANT;
  2702. push_error(vformat(R"(Cannot use subscript operator on a base of type "%s".)", base_type.to_string()), p_subscript->base);
  2703. break;
  2704. // Return int.
  2705. case Variant::PACKED_BYTE_ARRAY:
  2706. case Variant::PACKED_INT32_ARRAY:
  2707. case Variant::PACKED_INT64_ARRAY:
  2708. case Variant::VECTOR2I:
  2709. case Variant::VECTOR3I:
  2710. result_type.builtin_type = Variant::INT;
  2711. break;
  2712. // Return float.
  2713. case Variant::PACKED_FLOAT32_ARRAY:
  2714. case Variant::PACKED_FLOAT64_ARRAY:
  2715. case Variant::VECTOR2:
  2716. case Variant::VECTOR3:
  2717. case Variant::QUATERNION:
  2718. result_type.builtin_type = Variant::FLOAT;
  2719. break;
  2720. // Return Color.
  2721. case Variant::PACKED_COLOR_ARRAY:
  2722. result_type.builtin_type = Variant::COLOR;
  2723. break;
  2724. // Return String.
  2725. case Variant::PACKED_STRING_ARRAY:
  2726. case Variant::STRING:
  2727. result_type.builtin_type = Variant::STRING;
  2728. break;
  2729. // Return Vector2.
  2730. case Variant::PACKED_VECTOR2_ARRAY:
  2731. case Variant::TRANSFORM2D:
  2732. case Variant::RECT2:
  2733. result_type.builtin_type = Variant::VECTOR2;
  2734. break;
  2735. // Return Vector2I.
  2736. case Variant::RECT2I:
  2737. result_type.builtin_type = Variant::VECTOR2I;
  2738. break;
  2739. // Return Vector3.
  2740. case Variant::PACKED_VECTOR3_ARRAY:
  2741. case Variant::AABB:
  2742. case Variant::BASIS:
  2743. result_type.builtin_type = Variant::VECTOR3;
  2744. break;
  2745. // Depends on the index.
  2746. case Variant::TRANSFORM3D:
  2747. case Variant::PLANE:
  2748. case Variant::COLOR:
  2749. case Variant::DICTIONARY:
  2750. result_type.kind = GDScriptParser::DataType::VARIANT;
  2751. result_type.type_source = GDScriptParser::DataType::UNDETECTED;
  2752. break;
  2753. // Can have an element type.
  2754. case Variant::ARRAY:
  2755. if (base_type.has_container_element_type()) {
  2756. result_type = base_type.get_container_element_type();
  2757. result_type.type_source = base_type.type_source;
  2758. } else {
  2759. result_type.kind = GDScriptParser::DataType::VARIANT;
  2760. result_type.type_source = GDScriptParser::DataType::UNDETECTED;
  2761. }
  2762. break;
  2763. // Here for completeness.
  2764. case Variant::OBJECT:
  2765. case Variant::VARIANT_MAX:
  2766. break;
  2767. }
  2768. }
  2769. }
  2770. }
  2771. p_subscript->set_datatype(result_type);
  2772. }
  2773. void GDScriptAnalyzer::reduce_ternary_op(GDScriptParser::TernaryOpNode *p_ternary_op) {
  2774. reduce_expression(p_ternary_op->condition);
  2775. reduce_expression(p_ternary_op->true_expr);
  2776. reduce_expression(p_ternary_op->false_expr);
  2777. GDScriptParser::DataType result;
  2778. if (p_ternary_op->condition && p_ternary_op->condition->is_constant && p_ternary_op->true_expr->is_constant && p_ternary_op->false_expr && p_ternary_op->false_expr->is_constant) {
  2779. p_ternary_op->is_constant = true;
  2780. if (p_ternary_op->condition->reduced_value.booleanize()) {
  2781. p_ternary_op->reduced_value = p_ternary_op->true_expr->reduced_value;
  2782. } else {
  2783. p_ternary_op->reduced_value = p_ternary_op->false_expr->reduced_value;
  2784. }
  2785. }
  2786. GDScriptParser::DataType true_type;
  2787. if (p_ternary_op->true_expr) {
  2788. true_type = p_ternary_op->true_expr->get_datatype();
  2789. } else {
  2790. true_type.kind = GDScriptParser::DataType::VARIANT;
  2791. }
  2792. GDScriptParser::DataType false_type;
  2793. if (p_ternary_op->false_expr) {
  2794. false_type = p_ternary_op->false_expr->get_datatype();
  2795. } else {
  2796. false_type.kind = GDScriptParser::DataType::VARIANT;
  2797. }
  2798. if (true_type.is_variant() || false_type.is_variant()) {
  2799. result.kind = GDScriptParser::DataType::VARIANT;
  2800. } else {
  2801. result = true_type;
  2802. if (!is_type_compatible(true_type, false_type)) {
  2803. result = false_type;
  2804. if (!is_type_compatible(false_type, true_type)) {
  2805. result.type_source = GDScriptParser::DataType::UNDETECTED;
  2806. result.kind = GDScriptParser::DataType::VARIANT;
  2807. #ifdef DEBUG_ENABLED
  2808. parser->push_warning(p_ternary_op, GDScriptWarning::INCOMPATIBLE_TERNARY);
  2809. #endif
  2810. }
  2811. }
  2812. }
  2813. p_ternary_op->set_datatype(result);
  2814. }
  2815. void GDScriptAnalyzer::reduce_unary_op(GDScriptParser::UnaryOpNode *p_unary_op) {
  2816. reduce_expression(p_unary_op->operand);
  2817. GDScriptParser::DataType result;
  2818. if (p_unary_op->operand == nullptr) {
  2819. result.kind = GDScriptParser::DataType::VARIANT;
  2820. p_unary_op->set_datatype(result);
  2821. return;
  2822. }
  2823. if (p_unary_op->operand->is_constant) {
  2824. p_unary_op->is_constant = true;
  2825. p_unary_op->reduced_value = Variant::evaluate(p_unary_op->variant_op, p_unary_op->operand->reduced_value, Variant());
  2826. result = type_from_variant(p_unary_op->reduced_value, p_unary_op);
  2827. } else if (p_unary_op->operand->get_datatype().is_variant()) {
  2828. result.kind = GDScriptParser::DataType::VARIANT;
  2829. mark_node_unsafe(p_unary_op);
  2830. } else {
  2831. bool valid = false;
  2832. result = get_operation_type(p_unary_op->variant_op, p_unary_op->operand->get_datatype(), valid, p_unary_op);
  2833. if (!valid) {
  2834. push_error(vformat(R"(Invalid operand of type "%s" for unary operator "%s".)", p_unary_op->operand->get_datatype().to_string(), Variant::get_operator_name(p_unary_op->variant_op)), p_unary_op->operand);
  2835. }
  2836. }
  2837. p_unary_op->set_datatype(result);
  2838. }
  2839. void GDScriptAnalyzer::const_fold_array(GDScriptParser::ArrayNode *p_array) {
  2840. bool all_is_constant = true;
  2841. for (int i = 0; i < p_array->elements.size(); i++) {
  2842. GDScriptParser::ExpressionNode *element = p_array->elements[i];
  2843. all_is_constant = all_is_constant && element->is_constant;
  2844. if (!all_is_constant) {
  2845. return;
  2846. }
  2847. }
  2848. Array array;
  2849. array.resize(p_array->elements.size());
  2850. for (int i = 0; i < p_array->elements.size(); i++) {
  2851. array[i] = p_array->elements[i]->reduced_value;
  2852. }
  2853. p_array->is_constant = true;
  2854. p_array->reduced_value = array;
  2855. }
  2856. void GDScriptAnalyzer::const_fold_dictionary(GDScriptParser::DictionaryNode *p_dictionary) {
  2857. bool all_is_constant = true;
  2858. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  2859. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  2860. all_is_constant = all_is_constant && element.key->is_constant && element.value->is_constant;
  2861. if (!all_is_constant) {
  2862. return;
  2863. }
  2864. }
  2865. Dictionary dict;
  2866. for (int i = 0; i < p_dictionary->elements.size(); i++) {
  2867. const GDScriptParser::DictionaryNode::Pair &element = p_dictionary->elements[i];
  2868. dict[element.key->reduced_value] = element.value->reduced_value;
  2869. }
  2870. p_dictionary->is_constant = true;
  2871. p_dictionary->reduced_value = dict;
  2872. }
  2873. GDScriptParser::DataType GDScriptAnalyzer::type_from_variant(const Variant &p_value, const GDScriptParser::Node *p_source) {
  2874. GDScriptParser::DataType result;
  2875. result.is_constant = true;
  2876. result.kind = GDScriptParser::DataType::BUILTIN;
  2877. result.builtin_type = p_value.get_type();
  2878. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; // Constant has explicit type.
  2879. if (p_value.get_type() == Variant::OBJECT) {
  2880. Object *obj = p_value;
  2881. if (!obj) {
  2882. return GDScriptParser::DataType();
  2883. }
  2884. result.native_type = obj->get_class_name();
  2885. Ref<Script> scr = p_value; // Check if value is a script itself.
  2886. if (scr.is_valid()) {
  2887. result.is_meta_type = true;
  2888. } else {
  2889. result.is_meta_type = false;
  2890. scr = obj->get_script();
  2891. }
  2892. if (scr.is_valid()) {
  2893. if (scr->is_valid()) {
  2894. result.script_type = scr;
  2895. result.script_path = scr->get_path();
  2896. Ref<GDScript> gds = scr;
  2897. if (gds.is_valid()) {
  2898. result.kind = GDScriptParser::DataType::CLASS;
  2899. // This might be an inner class, so we want to get the parser for the root.
  2900. // But still get the inner class from that tree.
  2901. GDScript *current = gds.ptr();
  2902. List<StringName> class_chain;
  2903. while (current->_owner) {
  2904. // Push to front so it's in reverse.
  2905. class_chain.push_front(current->name);
  2906. current = current->_owner;
  2907. }
  2908. Ref<GDScriptParserRef> ref = get_parser_for(current->path);
  2909. ref->raise_status(GDScriptParserRef::INTERFACE_SOLVED);
  2910. GDScriptParser::ClassNode *found = ref->get_parser()->head;
  2911. // It should be okay to assume this exists, since we have a complete script already.
  2912. for (const StringName &E : class_chain) {
  2913. found = found->get_member(E).m_class;
  2914. }
  2915. result.class_type = found;
  2916. result.script_path = ref->get_parser()->script_path;
  2917. } else {
  2918. result.kind = GDScriptParser::DataType::SCRIPT;
  2919. }
  2920. result.native_type = scr->get_instance_base_type();
  2921. } else {
  2922. push_error(vformat(R"(Constant value uses script from "%s" which is loaded but not compiled.)", scr->get_path()), p_source);
  2923. result.kind = GDScriptParser::DataType::VARIANT;
  2924. result.type_source = GDScriptParser::DataType::UNDETECTED;
  2925. result.is_meta_type = false;
  2926. }
  2927. } else {
  2928. result.kind = GDScriptParser::DataType::NATIVE;
  2929. if (result.native_type == GDScriptNativeClass::get_class_static()) {
  2930. result.is_meta_type = true;
  2931. }
  2932. }
  2933. }
  2934. return result;
  2935. }
  2936. GDScriptParser::DataType GDScriptAnalyzer::type_from_metatype(const GDScriptParser::DataType &p_meta_type) const {
  2937. GDScriptParser::DataType result = p_meta_type;
  2938. result.is_meta_type = false;
  2939. result.is_constant = false;
  2940. return result;
  2941. }
  2942. GDScriptParser::DataType GDScriptAnalyzer::type_from_property(const PropertyInfo &p_property) const {
  2943. GDScriptParser::DataType result;
  2944. result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2945. if (p_property.type == Variant::NIL && (p_property.usage & PROPERTY_USAGE_NIL_IS_VARIANT)) {
  2946. // Variant
  2947. result.kind = GDScriptParser::DataType::VARIANT;
  2948. return result;
  2949. }
  2950. result.builtin_type = p_property.type;
  2951. if (p_property.type == Variant::OBJECT) {
  2952. result.kind = GDScriptParser::DataType::NATIVE;
  2953. result.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name;
  2954. } else {
  2955. result.kind = GDScriptParser::DataType::BUILTIN;
  2956. result.builtin_type = p_property.type;
  2957. if (p_property.type == Variant::ARRAY && p_property.hint == PROPERTY_HINT_ARRAY_TYPE) {
  2958. // Check element type.
  2959. StringName elem_type_name = p_property.hint_string;
  2960. GDScriptParser::DataType elem_type;
  2961. elem_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  2962. Variant::Type elem_builtin_type = GDScriptParser::get_builtin_type(elem_type_name);
  2963. if (elem_builtin_type < Variant::VARIANT_MAX) {
  2964. // Builtin type.
  2965. elem_type.kind = GDScriptParser::DataType::BUILTIN;
  2966. elem_type.builtin_type = elem_builtin_type;
  2967. } else if (class_exists(elem_type_name)) {
  2968. elem_type.kind = GDScriptParser::DataType::NATIVE;
  2969. elem_type.builtin_type = Variant::OBJECT;
  2970. elem_type.native_type = p_property.hint_string;
  2971. } else if (ScriptServer::is_global_class(elem_type_name)) {
  2972. // Just load this as it shouldn't be a GDScript.
  2973. Ref<Script> script = ResourceLoader::load(ScriptServer::get_global_class_path(elem_type_name));
  2974. elem_type.kind = GDScriptParser::DataType::SCRIPT;
  2975. elem_type.builtin_type = Variant::OBJECT;
  2976. elem_type.native_type = script->get_instance_base_type();
  2977. elem_type.script_type = script;
  2978. } else {
  2979. ERR_FAIL_V_MSG(result, "Could not find element type from property hint of a typed array.");
  2980. }
  2981. result.set_container_element_type(elem_type);
  2982. }
  2983. }
  2984. return result;
  2985. }
  2986. bool GDScriptAnalyzer::get_function_signature(GDScriptParser::CallNode *p_source, GDScriptParser::DataType p_base_type, const StringName &p_function, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) {
  2987. r_static = false;
  2988. r_vararg = false;
  2989. r_default_arg_count = 0;
  2990. StringName function_name = p_function;
  2991. if (p_base_type.kind == GDScriptParser::DataType::BUILTIN) {
  2992. // Construct a base type to get methods.
  2993. Callable::CallError err;
  2994. Variant dummy;
  2995. Variant::construct(p_base_type.builtin_type, dummy, nullptr, 0, err);
  2996. if (err.error != Callable::CallError::CALL_OK) {
  2997. ERR_FAIL_V_MSG(false, "Could not construct base Variant type.");
  2998. }
  2999. List<MethodInfo> methods;
  3000. dummy.get_method_list(&methods);
  3001. for (const MethodInfo &E : methods) {
  3002. if (E.name == p_function) {
  3003. function_signature_from_info(E, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  3004. r_static = Variant::is_builtin_method_static(p_base_type.builtin_type, function_name);
  3005. return true;
  3006. }
  3007. }
  3008. return false;
  3009. }
  3010. bool is_constructor = (p_base_type.is_meta_type || (p_source->callee && p_source->callee->type == GDScriptParser::Node::IDENTIFIER)) && p_function == StaticCString::create("new");
  3011. if (is_constructor) {
  3012. function_name = "_init";
  3013. r_static = true;
  3014. }
  3015. GDScriptParser::ClassNode *base_class = p_base_type.class_type;
  3016. GDScriptParser::FunctionNode *found_function = nullptr;
  3017. while (found_function == nullptr && base_class != nullptr) {
  3018. if (base_class->has_member(function_name)) {
  3019. if (base_class->get_member(function_name).type != GDScriptParser::ClassNode::Member::FUNCTION) {
  3020. // TODO: If this is Callable it can have a better error message.
  3021. push_error(vformat(R"(Member "%s" is not a function.)", function_name), p_source);
  3022. return false;
  3023. }
  3024. found_function = base_class->get_member(function_name).function;
  3025. }
  3026. base_class = base_class->base_type.class_type;
  3027. }
  3028. if (found_function != nullptr) {
  3029. r_static = is_constructor || found_function->is_static;
  3030. for (int i = 0; i < found_function->parameters.size(); i++) {
  3031. r_par_types.push_back(found_function->parameters[i]->get_datatype());
  3032. if (found_function->parameters[i]->default_value != nullptr) {
  3033. r_default_arg_count++;
  3034. }
  3035. }
  3036. r_return_type = found_function->get_datatype();
  3037. r_return_type.is_meta_type = false;
  3038. r_return_type.is_coroutine = found_function->is_coroutine;
  3039. return true;
  3040. }
  3041. Ref<Script> base_script = p_base_type.script_type;
  3042. while (base_script.is_valid() && base_script->is_valid()) {
  3043. MethodInfo info = base_script->get_method_info(function_name);
  3044. if (!(info == MethodInfo())) {
  3045. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  3046. }
  3047. base_script = base_script->get_base_script();
  3048. }
  3049. // If the base is a script, it might be trying to access members of the Script class itself.
  3050. if (p_base_type.is_meta_type && !is_constructor && (p_base_type.kind == GDScriptParser::DataType::SCRIPT || p_base_type.kind == GDScriptParser::DataType::CLASS)) {
  3051. MethodInfo info;
  3052. StringName script_class = p_base_type.kind == GDScriptParser::DataType::SCRIPT ? p_base_type.script_type->get_class_name() : StringName(GDScript::get_class_static());
  3053. if (ClassDB::get_method_info(script_class, function_name, &info)) {
  3054. return function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  3055. }
  3056. }
  3057. StringName base_native = p_base_type.native_type;
  3058. #ifdef DEBUG_ENABLED
  3059. if (base_native != StringName()) {
  3060. // Empty native class might happen in some Script implementations.
  3061. // Just ignore it.
  3062. if (!class_exists(base_native)) {
  3063. ERR_FAIL_V_MSG(false, vformat("Native class %s used in script doesn't exist or isn't exposed.", base_native));
  3064. }
  3065. }
  3066. #endif
  3067. if (is_constructor) {
  3068. // Native types always have a default constructor.
  3069. r_return_type = p_base_type;
  3070. r_return_type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  3071. r_return_type.is_meta_type = false;
  3072. return true;
  3073. }
  3074. MethodInfo info;
  3075. if (ClassDB::get_method_info(base_native, function_name, &info)) {
  3076. bool valid = function_signature_from_info(info, r_return_type, r_par_types, r_default_arg_count, r_static, r_vararg);
  3077. if (valid && Engine::get_singleton()->has_singleton(base_native)) {
  3078. r_static = true;
  3079. }
  3080. return valid;
  3081. }
  3082. return false;
  3083. }
  3084. bool GDScriptAnalyzer::function_signature_from_info(const MethodInfo &p_info, GDScriptParser::DataType &r_return_type, List<GDScriptParser::DataType> &r_par_types, int &r_default_arg_count, bool &r_static, bool &r_vararg) {
  3085. r_return_type = type_from_property(p_info.return_val);
  3086. r_default_arg_count = p_info.default_arguments.size();
  3087. r_vararg = (p_info.flags & METHOD_FLAG_VARARG) != 0;
  3088. for (const PropertyInfo &E : p_info.arguments) {
  3089. r_par_types.push_back(type_from_property(E));
  3090. }
  3091. return true;
  3092. }
  3093. bool GDScriptAnalyzer::validate_call_arg(const MethodInfo &p_method, const GDScriptParser::CallNode *p_call) {
  3094. List<GDScriptParser::DataType> arg_types;
  3095. for (const PropertyInfo &E : p_method.arguments) {
  3096. arg_types.push_back(type_from_property(E));
  3097. }
  3098. return validate_call_arg(arg_types, p_method.default_arguments.size(), (p_method.flags & METHOD_FLAG_VARARG) != 0, p_call);
  3099. }
  3100. bool GDScriptAnalyzer::validate_call_arg(const List<GDScriptParser::DataType> &p_par_types, int p_default_args_count, bool p_is_vararg, const GDScriptParser::CallNode *p_call) {
  3101. bool valid = true;
  3102. if (p_call->arguments.size() < p_par_types.size() - p_default_args_count) {
  3103. push_error(vformat(R"*(Too few arguments for "%s()" call. Expected at least %d but received %d.)*", p_call->function_name, p_par_types.size() - p_default_args_count, p_call->arguments.size()), p_call);
  3104. valid = false;
  3105. }
  3106. if (!p_is_vararg && p_call->arguments.size() > p_par_types.size()) {
  3107. push_error(vformat(R"*(Too many arguments for "%s()" call. Expected at most %d but received %d.)*", p_call->function_name, p_par_types.size(), p_call->arguments.size()), p_call->arguments[p_par_types.size()]);
  3108. valid = false;
  3109. }
  3110. for (int i = 0; i < p_call->arguments.size(); i++) {
  3111. if (i >= p_par_types.size()) {
  3112. // Already on vararg place.
  3113. break;
  3114. }
  3115. GDScriptParser::DataType par_type = p_par_types[i];
  3116. GDScriptParser::DataType arg_type = p_call->arguments[i]->get_datatype();
  3117. if (arg_type.is_variant()) {
  3118. // Argument can be anything, so this is unsafe.
  3119. mark_node_unsafe(p_call->arguments[i]);
  3120. } else if (par_type.is_hard_type() && !is_type_compatible(par_type, arg_type, true)) {
  3121. // Supertypes are acceptable for dynamic compliance, but it's unsafe.
  3122. mark_node_unsafe(p_call);
  3123. if (!is_type_compatible(arg_type, par_type)) {
  3124. push_error(vformat(R"*(Invalid argument for "%s()" function: argument %d should be %s but is %s.)*",
  3125. p_call->function_name, i + 1, par_type.to_string(), arg_type.to_string()),
  3126. p_call->arguments[i]);
  3127. valid = false;
  3128. }
  3129. #ifdef DEBUG_ENABLED
  3130. } else {
  3131. if (par_type.kind == GDScriptParser::DataType::BUILTIN && par_type.builtin_type == Variant::INT && arg_type.kind == GDScriptParser::DataType::BUILTIN && arg_type.builtin_type == Variant::FLOAT) {
  3132. parser->push_warning(p_call, GDScriptWarning::NARROWING_CONVERSION, p_call->function_name);
  3133. }
  3134. #endif
  3135. }
  3136. }
  3137. return valid;
  3138. }
  3139. #ifdef DEBUG_ENABLED
  3140. bool GDScriptAnalyzer::is_shadowing(GDScriptParser::IdentifierNode *p_local, const String &p_context) {
  3141. const StringName &name = p_local->name;
  3142. GDScriptParser::DataType base = parser->current_class->get_datatype();
  3143. GDScriptParser::ClassNode *base_class = base.class_type;
  3144. while (base_class != nullptr) {
  3145. if (base_class->has_member(name)) {
  3146. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE, p_context, p_local->name, base_class->get_member(name).get_type_name(), itos(base_class->get_member(name).get_line()));
  3147. return true;
  3148. }
  3149. base_class = base_class->base_type.class_type;
  3150. }
  3151. StringName base_native = base.native_type;
  3152. ERR_FAIL_COND_V_MSG(!class_exists(base_native), false, "Non-existent native base class.");
  3153. StringName parent = base_native;
  3154. while (parent != StringName()) {
  3155. if (ClassDB::has_method(parent, name, true)) {
  3156. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "method", parent);
  3157. return true;
  3158. } else if (ClassDB::has_signal(parent, name, true)) {
  3159. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "signal", parent);
  3160. return true;
  3161. } else if (ClassDB::has_property(parent, name, true)) {
  3162. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "property", parent);
  3163. return true;
  3164. } else if (ClassDB::has_integer_constant(parent, name, true)) {
  3165. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "constant", parent);
  3166. return true;
  3167. } else if (ClassDB::has_enum(parent, name, true)) {
  3168. parser->push_warning(p_local, GDScriptWarning::SHADOWED_VARIABLE_BASE_CLASS, p_context, p_local->name, "enum", parent);
  3169. return true;
  3170. }
  3171. parent = ClassDB::get_parent_class(parent);
  3172. }
  3173. return false;
  3174. }
  3175. #endif
  3176. GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, bool &r_valid, const GDScriptParser::Node *p_source) {
  3177. // Unary version.
  3178. GDScriptParser::DataType nil_type;
  3179. nil_type.builtin_type = Variant::NIL;
  3180. return get_operation_type(p_operation, p_a, nil_type, r_valid, p_source);
  3181. }
  3182. GDScriptParser::DataType GDScriptAnalyzer::get_operation_type(Variant::Operator p_operation, const GDScriptParser::DataType &p_a, const GDScriptParser::DataType &p_b, bool &r_valid, const GDScriptParser::Node *p_source) {
  3183. GDScriptParser::DataType result;
  3184. result.kind = GDScriptParser::DataType::VARIANT;
  3185. Variant::Type a_type = p_a.builtin_type;
  3186. Variant::Type b_type = p_b.builtin_type;
  3187. Variant::ValidatedOperatorEvaluator op_eval = Variant::get_validated_operator_evaluator(p_operation, a_type, b_type);
  3188. if (op_eval == nullptr) {
  3189. r_valid = false;
  3190. return result;
  3191. }
  3192. r_valid = true;
  3193. result.type_source = GDScriptParser::DataType::ANNOTATED_INFERRED;
  3194. result.kind = GDScriptParser::DataType::BUILTIN;
  3195. result.builtin_type = Variant::get_operator_return_type(p_operation, a_type, b_type);
  3196. return result;
  3197. }
  3198. // TODO: Add safe/unsafe return variable (for variant cases)
  3199. bool GDScriptAnalyzer::is_type_compatible(const GDScriptParser::DataType &p_target, const GDScriptParser::DataType &p_source, bool p_allow_implicit_conversion) const {
  3200. // These return "true" so it doesn't affect users negatively.
  3201. ERR_FAIL_COND_V_MSG(!p_target.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset target type");
  3202. ERR_FAIL_COND_V_MSG(!p_source.is_set(), true, "Parser bug (please report): Trying to check compatibility of unset value type");
  3203. if (p_target.kind == GDScriptParser::DataType::VARIANT) {
  3204. // Variant can receive anything.
  3205. return true;
  3206. }
  3207. if (p_source.kind == GDScriptParser::DataType::VARIANT) {
  3208. // TODO: This is acceptable but unsafe. Make sure unsafe line is set.
  3209. return true;
  3210. }
  3211. if (p_target.kind == GDScriptParser::DataType::BUILTIN) {
  3212. bool valid = p_source.kind == GDScriptParser::DataType::BUILTIN && p_target.builtin_type == p_source.builtin_type;
  3213. if (!valid && p_allow_implicit_conversion) {
  3214. valid = Variant::can_convert_strict(p_source.builtin_type, p_target.builtin_type);
  3215. }
  3216. if (!valid && p_target.builtin_type == Variant::INT && p_source.kind == GDScriptParser::DataType::ENUM_VALUE) {
  3217. // Enum value is also integer.
  3218. valid = true;
  3219. }
  3220. if (valid && p_target.builtin_type == Variant::ARRAY && p_source.builtin_type == Variant::ARRAY) {
  3221. // Check the element type.
  3222. if (p_target.has_container_element_type()) {
  3223. if (!p_source.has_container_element_type()) {
  3224. // TODO: Maybe this is valid but unsafe?
  3225. // Variant array can't be appended to typed array.
  3226. valid = false;
  3227. } else {
  3228. valid = is_type_compatible(p_target.get_container_element_type(), p_source.get_container_element_type(), false);
  3229. }
  3230. }
  3231. }
  3232. return valid;
  3233. }
  3234. if (p_target.kind == GDScriptParser::DataType::ENUM) {
  3235. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::INT) {
  3236. return true;
  3237. }
  3238. if (p_source.kind == GDScriptParser::DataType::ENUM_VALUE) {
  3239. if (p_source.native_type == p_target.native_type && p_target.enum_values.has(p_source.enum_type)) {
  3240. return true;
  3241. }
  3242. }
  3243. return false;
  3244. }
  3245. // From here on the target type is an object, so we have to test polymorphism.
  3246. if (p_source.kind == GDScriptParser::DataType::BUILTIN && p_source.builtin_type == Variant::NIL) {
  3247. // null is acceptable in object.
  3248. return true;
  3249. }
  3250. StringName src_native;
  3251. Ref<Script> src_script;
  3252. const GDScriptParser::ClassNode *src_class = nullptr;
  3253. switch (p_source.kind) {
  3254. case GDScriptParser::DataType::NATIVE:
  3255. if (p_target.kind != GDScriptParser::DataType::NATIVE) {
  3256. // Non-native class cannot be supertype of native.
  3257. return false;
  3258. }
  3259. if (p_source.is_meta_type) {
  3260. src_native = GDScriptNativeClass::get_class_static();
  3261. } else {
  3262. src_native = p_source.native_type;
  3263. }
  3264. break;
  3265. case GDScriptParser::DataType::SCRIPT:
  3266. if (p_target.kind == GDScriptParser::DataType::CLASS) {
  3267. // A script type cannot be a subtype of a GDScript class.
  3268. return false;
  3269. }
  3270. if (p_source.is_meta_type) {
  3271. src_native = p_source.script_type->get_class_name();
  3272. } else {
  3273. src_script = p_source.script_type;
  3274. src_native = src_script->get_instance_base_type();
  3275. }
  3276. break;
  3277. case GDScriptParser::DataType::CLASS:
  3278. if (p_source.is_meta_type) {
  3279. src_native = GDScript::get_class_static();
  3280. } else {
  3281. src_class = p_source.class_type;
  3282. const GDScriptParser::ClassNode *base = src_class;
  3283. while (base->base_type.kind == GDScriptParser::DataType::CLASS) {
  3284. base = base->base_type.class_type;
  3285. }
  3286. src_native = base->base_type.native_type;
  3287. src_script = base->base_type.script_type;
  3288. }
  3289. break;
  3290. case GDScriptParser::DataType::VARIANT:
  3291. case GDScriptParser::DataType::BUILTIN:
  3292. case GDScriptParser::DataType::ENUM:
  3293. case GDScriptParser::DataType::ENUM_VALUE:
  3294. case GDScriptParser::DataType::UNRESOLVED:
  3295. break; // Already solved before.
  3296. }
  3297. switch (p_target.kind) {
  3298. case GDScriptParser::DataType::NATIVE: {
  3299. if (p_target.is_meta_type) {
  3300. return ClassDB::is_parent_class(src_native, GDScriptNativeClass::get_class_static());
  3301. }
  3302. return ClassDB::is_parent_class(src_native, p_target.native_type);
  3303. }
  3304. case GDScriptParser::DataType::SCRIPT:
  3305. if (p_target.is_meta_type) {
  3306. return ClassDB::is_parent_class(src_native, p_target.script_type->get_class_name());
  3307. }
  3308. while (src_script.is_valid()) {
  3309. if (src_script == p_target.script_type) {
  3310. return true;
  3311. }
  3312. src_script = src_script->get_base_script();
  3313. }
  3314. return false;
  3315. case GDScriptParser::DataType::CLASS:
  3316. if (p_target.is_meta_type) {
  3317. return ClassDB::is_parent_class(src_native, GDScript::get_class_static());
  3318. }
  3319. while (src_class != nullptr) {
  3320. if (src_class->fqcn == p_target.class_type->fqcn) {
  3321. return true;
  3322. }
  3323. src_class = src_class->base_type.class_type;
  3324. }
  3325. return false;
  3326. case GDScriptParser::DataType::VARIANT:
  3327. case GDScriptParser::DataType::BUILTIN:
  3328. case GDScriptParser::DataType::ENUM:
  3329. case GDScriptParser::DataType::ENUM_VALUE:
  3330. case GDScriptParser::DataType::UNRESOLVED:
  3331. break; // Already solved before.
  3332. }
  3333. return false;
  3334. }
  3335. void GDScriptAnalyzer::push_error(const String &p_message, const GDScriptParser::Node *p_origin) {
  3336. mark_node_unsafe(p_origin);
  3337. parser->push_error(p_message, p_origin);
  3338. }
  3339. void GDScriptAnalyzer::mark_node_unsafe(const GDScriptParser::Node *p_node) {
  3340. #ifdef DEBUG_ENABLED
  3341. for (int i = p_node->start_line; i <= p_node->end_line; i++) {
  3342. parser->unsafe_lines.insert(i);
  3343. }
  3344. #endif
  3345. }
  3346. bool GDScriptAnalyzer::class_exists(const StringName &p_class) const {
  3347. return ClassDB::class_exists(p_class) && ClassDB::is_class_exposed(p_class);
  3348. }
  3349. Ref<GDScriptParserRef> GDScriptAnalyzer::get_parser_for(const String &p_path) {
  3350. Ref<GDScriptParserRef> ref;
  3351. if (depended_parsers.has(p_path)) {
  3352. ref = depended_parsers[p_path];
  3353. } else {
  3354. Error err = OK;
  3355. ref = GDScriptCache::get_parser(p_path, GDScriptParserRef::EMPTY, err, parser->script_path);
  3356. depended_parsers[p_path] = ref;
  3357. }
  3358. return ref;
  3359. }
  3360. Error GDScriptAnalyzer::resolve_inheritance() {
  3361. return resolve_inheritance(parser->head);
  3362. }
  3363. Error GDScriptAnalyzer::resolve_interface() {
  3364. resolve_class_interface(parser->head);
  3365. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  3366. }
  3367. Error GDScriptAnalyzer::resolve_body() {
  3368. resolve_class_body(parser->head);
  3369. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  3370. }
  3371. Error GDScriptAnalyzer::resolve_program() {
  3372. resolve_class_interface(parser->head);
  3373. resolve_class_body(parser->head);
  3374. List<String> parser_keys;
  3375. depended_parsers.get_key_list(&parser_keys);
  3376. for (const String &E : parser_keys) {
  3377. if (depended_parsers[E].is_null()) {
  3378. return ERR_PARSE_ERROR;
  3379. }
  3380. depended_parsers[E]->raise_status(GDScriptParserRef::FULLY_SOLVED);
  3381. }
  3382. return parser->errors.is_empty() ? OK : ERR_PARSE_ERROR;
  3383. }
  3384. Error GDScriptAnalyzer::analyze() {
  3385. parser->errors.clear();
  3386. Error err = resolve_inheritance(parser->head);
  3387. if (err) {
  3388. return err;
  3389. }
  3390. return resolve_program();
  3391. }
  3392. GDScriptAnalyzer::GDScriptAnalyzer(GDScriptParser *p_parser) {
  3393. parser = p_parser;
  3394. }