gdscript_analyzer.cpp 146 KB

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