gdscript_editor.cpp 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211
  1. /*************************************************************************/
  2. /* gdscript_editor.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "gdscript.h"
  31. #include "core/config/engine.h"
  32. #include "core/core_constants.h"
  33. #include "core/io/file_access.h"
  34. #include "editor_templates/templates.gen.h"
  35. #include "gdscript_analyzer.h"
  36. #include "gdscript_compiler.h"
  37. #include "gdscript_parser.h"
  38. #include "gdscript_tokenizer.h"
  39. #include "gdscript_utility_functions.h"
  40. #ifdef TOOLS_ENABLED
  41. #include "core/config/project_settings.h"
  42. #include "editor/editor_file_system.h"
  43. #include "editor/editor_settings.h"
  44. #endif
  45. void GDScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
  46. p_delimiters->push_back("#");
  47. }
  48. void GDScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const {
  49. p_delimiters->push_back("\" \"");
  50. p_delimiters->push_back("' '");
  51. p_delimiters->push_back("\"\"\" \"\"\"");
  52. }
  53. bool GDScriptLanguage::is_using_templates() {
  54. return true;
  55. }
  56. Ref<Script> GDScriptLanguage::make_template(const String &p_template, const String &p_class_name, const String &p_base_class_name) const {
  57. Ref<GDScript> script;
  58. script.instantiate();
  59. String processed_template = p_template;
  60. #ifdef TOOLS_ENABLED
  61. if (!EDITOR_GET("text_editor/completion/add_type_hints")) {
  62. processed_template = processed_template.replace(": int", "")
  63. .replace(": String", "")
  64. .replace(": float", "")
  65. .replace(":=", "=")
  66. .replace(" -> void", "");
  67. }
  68. #else
  69. processed_template = processed_template.replace(": int", "")
  70. .replace(": String", "")
  71. .replace(": float", "")
  72. .replace(" -> void", "");
  73. #endif
  74. processed_template = processed_template.replace("_BASE_", p_base_class_name)
  75. .replace("_CLASS_", p_class_name)
  76. .replace("_TS_", _get_indentation());
  77. script->set_source_code(processed_template);
  78. return script;
  79. }
  80. Vector<ScriptLanguage::ScriptTemplate> GDScriptLanguage::get_built_in_templates(StringName p_object) {
  81. Vector<ScriptLanguage::ScriptTemplate> templates;
  82. for (int i = 0; i < TEMPLATES_ARRAY_SIZE; i++) {
  83. if (TEMPLATES[i].inherit == p_object) {
  84. templates.append(TEMPLATES[i]);
  85. }
  86. }
  87. return templates;
  88. }
  89. static void get_function_names_recursively(const GDScriptParser::ClassNode *p_class, const String &p_prefix, Map<int, String> &r_funcs) {
  90. for (int i = 0; i < p_class->members.size(); i++) {
  91. if (p_class->members[i].type == GDScriptParser::ClassNode::Member::FUNCTION) {
  92. const GDScriptParser::FunctionNode *function = p_class->members[i].function;
  93. r_funcs[function->start_line] = p_prefix.is_empty() ? String(function->identifier->name) : p_prefix + "." + String(function->identifier->name);
  94. } else if (p_class->members[i].type == GDScriptParser::ClassNode::Member::CLASS) {
  95. String new_prefix = p_class->members[i].m_class->identifier->name;
  96. get_function_names_recursively(p_class->members[i].m_class, p_prefix.is_empty() ? new_prefix : p_prefix + "." + new_prefix, r_funcs);
  97. }
  98. }
  99. }
  100. bool GDScriptLanguage::validate(const String &p_script, const String &p_path, List<String> *r_functions, List<ScriptLanguage::ScriptError> *r_errors, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const {
  101. GDScriptParser parser;
  102. GDScriptAnalyzer analyzer(&parser);
  103. Error err = parser.parse(p_script, p_path, false);
  104. if (err == OK) {
  105. err = analyzer.analyze();
  106. }
  107. #ifdef DEBUG_ENABLED
  108. if (r_warnings) {
  109. for (const GDScriptWarning &E : parser.get_warnings()) {
  110. const GDScriptWarning &warn = E;
  111. ScriptLanguage::Warning w;
  112. w.start_line = warn.start_line;
  113. w.end_line = warn.end_line;
  114. w.leftmost_column = warn.leftmost_column;
  115. w.rightmost_column = warn.rightmost_column;
  116. w.code = (int)warn.code;
  117. w.string_code = GDScriptWarning::get_name_from_code(warn.code);
  118. w.message = warn.get_message();
  119. r_warnings->push_back(w);
  120. }
  121. }
  122. #endif
  123. if (err) {
  124. if (r_errors) {
  125. for (const GDScriptParser::ParserError &E : parser.get_errors()) {
  126. const GDScriptParser::ParserError &pe = E;
  127. ScriptLanguage::ScriptError e;
  128. e.line = pe.line;
  129. e.column = pe.column;
  130. e.message = pe.message;
  131. r_errors->push_back(e);
  132. }
  133. }
  134. return false;
  135. } else {
  136. const GDScriptParser::ClassNode *cl = parser.get_tree();
  137. Map<int, String> funcs;
  138. get_function_names_recursively(cl, "", funcs);
  139. for (const KeyValue<int, String> &E : funcs) {
  140. r_functions->push_back(E.value + ":" + itos(E.key));
  141. }
  142. }
  143. #ifdef DEBUG_ENABLED
  144. if (r_safe_lines) {
  145. const Set<int> &unsafe_lines = parser.get_unsafe_lines();
  146. for (int i = 1; i <= parser.get_last_line_number(); i++) {
  147. if (!unsafe_lines.has(i)) {
  148. r_safe_lines->insert(i);
  149. }
  150. }
  151. }
  152. #endif
  153. return true;
  154. }
  155. bool GDScriptLanguage::has_named_classes() const {
  156. return false;
  157. }
  158. bool GDScriptLanguage::supports_builtin_mode() const {
  159. return true;
  160. }
  161. bool GDScriptLanguage::supports_documentation() const {
  162. return true;
  163. }
  164. int GDScriptLanguage::find_function(const String &p_function, const String &p_code) const {
  165. GDScriptTokenizer tokenizer;
  166. tokenizer.set_source_code(p_code);
  167. int indent = 0;
  168. GDScriptTokenizer::Token current = tokenizer.scan();
  169. while (current.type != GDScriptTokenizer::Token::TK_EOF && current.type != GDScriptTokenizer::Token::ERROR) {
  170. if (current.type == GDScriptTokenizer::Token::INDENT) {
  171. indent++;
  172. } else if (current.type == GDScriptTokenizer::Token::DEDENT) {
  173. indent--;
  174. }
  175. if (indent == 0 && current.type == GDScriptTokenizer::Token::FUNC) {
  176. current = tokenizer.scan();
  177. if (current.is_identifier()) {
  178. String identifier = current.get_identifier();
  179. if (identifier == p_function) {
  180. return current.start_line;
  181. }
  182. }
  183. }
  184. current = tokenizer.scan();
  185. }
  186. return -1;
  187. }
  188. Script *GDScriptLanguage::create_script() const {
  189. return memnew(GDScript);
  190. }
  191. /* DEBUGGER FUNCTIONS */
  192. bool GDScriptLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
  193. // break because of parse error
  194. if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
  195. _debug_parse_err_line = p_line;
  196. _debug_parse_err_file = p_file;
  197. _debug_error = p_error;
  198. EngineDebugger::get_script_debugger()->debug(this, false, true);
  199. return true;
  200. } else {
  201. return false;
  202. }
  203. }
  204. bool GDScriptLanguage::debug_break(const String &p_error, bool p_allow_continue) {
  205. if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
  206. _debug_parse_err_line = -1;
  207. _debug_parse_err_file = "";
  208. _debug_error = p_error;
  209. bool is_error_breakpoint = p_error != "Breakpoint";
  210. EngineDebugger::get_script_debugger()->debug(this, p_allow_continue, is_error_breakpoint);
  211. return true;
  212. } else {
  213. return false;
  214. }
  215. }
  216. String GDScriptLanguage::debug_get_error() const {
  217. return _debug_error;
  218. }
  219. int GDScriptLanguage::debug_get_stack_level_count() const {
  220. if (_debug_parse_err_line >= 0) {
  221. return 1;
  222. }
  223. return _debug_call_stack_pos;
  224. }
  225. int GDScriptLanguage::debug_get_stack_level_line(int p_level) const {
  226. if (_debug_parse_err_line >= 0) {
  227. return _debug_parse_err_line;
  228. }
  229. ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, -1);
  230. int l = _debug_call_stack_pos - p_level - 1;
  231. return *(_call_stack[l].line);
  232. }
  233. String GDScriptLanguage::debug_get_stack_level_function(int p_level) const {
  234. if (_debug_parse_err_line >= 0) {
  235. return "";
  236. }
  237. ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, "");
  238. int l = _debug_call_stack_pos - p_level - 1;
  239. return _call_stack[l].function->get_name();
  240. }
  241. String GDScriptLanguage::debug_get_stack_level_source(int p_level) const {
  242. if (_debug_parse_err_line >= 0) {
  243. return _debug_parse_err_file;
  244. }
  245. ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, "");
  246. int l = _debug_call_stack_pos - p_level - 1;
  247. return _call_stack[l].function->get_source();
  248. }
  249. void GDScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
  250. if (_debug_parse_err_line >= 0) {
  251. return;
  252. }
  253. ERR_FAIL_INDEX(p_level, _debug_call_stack_pos);
  254. int l = _debug_call_stack_pos - p_level - 1;
  255. GDScriptFunction *f = _call_stack[l].function;
  256. List<Pair<StringName, int>> locals;
  257. f->debug_get_stack_member_state(*_call_stack[l].line, &locals);
  258. for (const Pair<StringName, int> &E : locals) {
  259. p_locals->push_back(E.first);
  260. p_values->push_back(_call_stack[l].stack[E.second]);
  261. }
  262. }
  263. void GDScriptLanguage::debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
  264. if (_debug_parse_err_line >= 0) {
  265. return;
  266. }
  267. ERR_FAIL_INDEX(p_level, _debug_call_stack_pos);
  268. int l = _debug_call_stack_pos - p_level - 1;
  269. GDScriptInstance *instance = _call_stack[l].instance;
  270. if (!instance) {
  271. return;
  272. }
  273. Ref<GDScript> script = instance->get_script();
  274. ERR_FAIL_COND(script.is_null());
  275. const Map<StringName, GDScript::MemberInfo> &mi = script->debug_get_member_indices();
  276. for (const KeyValue<StringName, GDScript::MemberInfo> &E : mi) {
  277. p_members->push_back(E.key);
  278. p_values->push_back(instance->debug_get_member_by_index(E.value.index));
  279. }
  280. }
  281. ScriptInstance *GDScriptLanguage::debug_get_stack_level_instance(int p_level) {
  282. if (_debug_parse_err_line >= 0) {
  283. return nullptr;
  284. }
  285. ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, nullptr);
  286. int l = _debug_call_stack_pos - p_level - 1;
  287. ScriptInstance *instance = _call_stack[l].instance;
  288. return instance;
  289. }
  290. void GDScriptLanguage::debug_get_globals(List<String> *p_globals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
  291. const Map<StringName, int> &name_idx = GDScriptLanguage::get_singleton()->get_global_map();
  292. const Variant *globals = GDScriptLanguage::get_singleton()->get_global_array();
  293. List<Pair<String, Variant>> cinfo;
  294. get_public_constants(&cinfo);
  295. for (const KeyValue<StringName, int> &E : name_idx) {
  296. if (ClassDB::class_exists(E.key) || Engine::get_singleton()->has_singleton(E.key)) {
  297. continue;
  298. }
  299. bool is_script_constant = false;
  300. for (List<Pair<String, Variant>>::Element *CE = cinfo.front(); CE; CE = CE->next()) {
  301. if (CE->get().first == E.key) {
  302. is_script_constant = true;
  303. break;
  304. }
  305. }
  306. if (is_script_constant) {
  307. continue;
  308. }
  309. const Variant &var = globals[E.value];
  310. if (Object *obj = var) {
  311. if (Object::cast_to<GDScriptNativeClass>(obj)) {
  312. continue;
  313. }
  314. }
  315. bool skip = false;
  316. for (int i = 0; i < CoreConstants::get_global_constant_count(); i++) {
  317. if (E.key == CoreConstants::get_global_constant_name(i)) {
  318. skip = true;
  319. break;
  320. }
  321. }
  322. if (skip) {
  323. continue;
  324. }
  325. p_globals->push_back(E.key);
  326. p_values->push_back(var);
  327. }
  328. }
  329. String GDScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) {
  330. return "";
  331. }
  332. void GDScriptLanguage::get_recognized_extensions(List<String> *p_extensions) const {
  333. p_extensions->push_back("gd");
  334. }
  335. void GDScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const {
  336. List<StringName> functions;
  337. GDScriptUtilityFunctions::get_function_list(&functions);
  338. for (const StringName &E : functions) {
  339. p_functions->push_back(GDScriptUtilityFunctions::get_function_info(E));
  340. }
  341. // Not really "functions", but show in documentation.
  342. {
  343. MethodInfo mi;
  344. mi.name = "preload";
  345. mi.arguments.push_back(PropertyInfo(Variant::STRING, "path"));
  346. mi.return_val = PropertyInfo(Variant::OBJECT, "", PROPERTY_HINT_RESOURCE_TYPE, "Resource");
  347. p_functions->push_back(mi);
  348. }
  349. {
  350. MethodInfo mi;
  351. mi.name = "assert";
  352. mi.return_val.type = Variant::NIL;
  353. mi.arguments.push_back(PropertyInfo(Variant::BOOL, "condition"));
  354. mi.arguments.push_back(PropertyInfo(Variant::STRING, "message"));
  355. mi.default_arguments.push_back(String());
  356. p_functions->push_back(mi);
  357. }
  358. }
  359. void GDScriptLanguage::get_public_constants(List<Pair<String, Variant>> *p_constants) const {
  360. Pair<String, Variant> pi;
  361. pi.first = "PI";
  362. pi.second = Math_PI;
  363. p_constants->push_back(pi);
  364. Pair<String, Variant> tau;
  365. tau.first = "TAU";
  366. tau.second = Math_TAU;
  367. p_constants->push_back(tau);
  368. Pair<String, Variant> infinity;
  369. infinity.first = "INF";
  370. infinity.second = INFINITY;
  371. p_constants->push_back(infinity);
  372. Pair<String, Variant> nan;
  373. nan.first = "NAN";
  374. nan.second = NAN;
  375. p_constants->push_back(nan);
  376. }
  377. String GDScriptLanguage::make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const {
  378. #ifdef TOOLS_ENABLED
  379. bool th = EditorSettings::get_singleton()->get_setting("text_editor/completion/add_type_hints");
  380. #else
  381. bool th = false;
  382. #endif
  383. String s = "func " + p_name + "(";
  384. if (p_args.size()) {
  385. for (int i = 0; i < p_args.size(); i++) {
  386. if (i > 0) {
  387. s += ", ";
  388. }
  389. s += p_args[i].get_slice(":", 0);
  390. if (th) {
  391. String type = p_args[i].get_slice(":", 1);
  392. if (!type.is_empty() && type != "var") {
  393. s += ": " + type;
  394. }
  395. }
  396. }
  397. }
  398. s += String(")") + (th ? " -> void" : "") + ":\n" + _get_indentation() + "pass # Replace with function body.\n";
  399. return s;
  400. }
  401. //////// COMPLETION //////////
  402. #ifdef TOOLS_ENABLED
  403. #define COMPLETION_RECURSION_LIMIT 200
  404. struct GDScriptCompletionIdentifier {
  405. GDScriptParser::DataType type;
  406. String enumeration;
  407. Variant value;
  408. const GDScriptParser::ExpressionNode *assigned_expression = nullptr;
  409. };
  410. static String _get_visual_datatype(const PropertyInfo &p_info, bool p_is_arg = true) {
  411. if (p_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
  412. String enum_name = p_info.class_name;
  413. if (!enum_name.contains(".")) {
  414. return enum_name;
  415. }
  416. return enum_name.get_slice(".", 1);
  417. }
  418. String n = p_info.name;
  419. int idx = n.find(":");
  420. if (idx != -1) {
  421. return n.substr(idx + 1, n.length());
  422. }
  423. if (p_info.type == Variant::OBJECT) {
  424. if (p_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
  425. return p_info.hint_string;
  426. } else {
  427. return p_info.class_name.operator String();
  428. }
  429. }
  430. if (p_info.type == Variant::NIL) {
  431. if (p_is_arg || (p_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT)) {
  432. return "Variant";
  433. } else {
  434. return "void";
  435. }
  436. }
  437. return Variant::get_type_name(p_info.type);
  438. }
  439. static String _make_arguments_hint(const MethodInfo &p_info, int p_arg_idx, bool p_is_annotation = false) {
  440. String arghint;
  441. if (!p_is_annotation) {
  442. arghint += _get_visual_datatype(p_info.return_val, false) + " ";
  443. }
  444. arghint += p_info.name + "(";
  445. int def_args = p_info.arguments.size() - p_info.default_arguments.size();
  446. int i = 0;
  447. for (const PropertyInfo &E : p_info.arguments) {
  448. if (i > 0) {
  449. arghint += ", ";
  450. }
  451. if (i == p_arg_idx) {
  452. arghint += String::chr(0xFFFF);
  453. }
  454. arghint += E.name + ": " + _get_visual_datatype(E, true);
  455. if (i - def_args >= 0) {
  456. arghint += String(" = ") + p_info.default_arguments[i - def_args].get_construct_string();
  457. }
  458. if (i == p_arg_idx) {
  459. arghint += String::chr(0xFFFF);
  460. }
  461. i++;
  462. }
  463. if (p_info.flags & METHOD_FLAG_VARARG) {
  464. if (p_info.arguments.size() > 0) {
  465. arghint += ", ";
  466. }
  467. if (p_arg_idx >= p_info.arguments.size()) {
  468. arghint += String::chr(0xFFFF);
  469. }
  470. arghint += "...";
  471. if (p_arg_idx >= p_info.arguments.size()) {
  472. arghint += String::chr(0xFFFF);
  473. }
  474. }
  475. arghint += ")";
  476. return arghint;
  477. }
  478. static String _make_arguments_hint(const GDScriptParser::FunctionNode *p_function, int p_arg_idx) {
  479. String arghint = p_function->get_datatype().to_string() + " " + p_function->identifier->name.operator String() + "(";
  480. for (int i = 0; i < p_function->parameters.size(); i++) {
  481. if (i > 0) {
  482. arghint += ", ";
  483. }
  484. if (i == p_arg_idx) {
  485. arghint += String::chr(0xFFFF);
  486. }
  487. const GDScriptParser::ParameterNode *par = p_function->parameters[i];
  488. arghint += par->identifier->name.operator String() + ": " + par->get_datatype().to_string();
  489. if (par->default_value) {
  490. String def_val = "<unknown>";
  491. switch (par->default_value->type) {
  492. case GDScriptParser::Node::LITERAL: {
  493. const GDScriptParser::LiteralNode *literal = static_cast<const GDScriptParser::LiteralNode *>(par->default_value);
  494. def_val = literal->value.get_construct_string();
  495. } break;
  496. case GDScriptParser::Node::IDENTIFIER: {
  497. const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(par->default_value);
  498. def_val = id->name.operator String();
  499. } break;
  500. case GDScriptParser::Node::CALL: {
  501. const GDScriptParser::CallNode *call = static_cast<const GDScriptParser::CallNode *>(par->default_value);
  502. if (call->is_constant && call->reduced) {
  503. def_val = call->function_name.operator String() + call->reduced_value.operator String();
  504. }
  505. } break;
  506. case GDScriptParser::Node::ARRAY: {
  507. const GDScriptParser::ArrayNode *arr = static_cast<const GDScriptParser::ArrayNode *>(par->default_value);
  508. if (arr->is_constant && arr->reduced) {
  509. def_val = arr->reduced_value.operator String();
  510. }
  511. } break;
  512. case GDScriptParser::Node::DICTIONARY: {
  513. const GDScriptParser::DictionaryNode *dict = static_cast<const GDScriptParser::DictionaryNode *>(par->default_value);
  514. if (dict->is_constant && dict->reduced) {
  515. def_val = dict->reduced_value.operator String();
  516. }
  517. } break;
  518. case GDScriptParser::Node::SUBSCRIPT: {
  519. const GDScriptParser::SubscriptNode *sub = static_cast<const GDScriptParser::SubscriptNode *>(par->default_value);
  520. if (sub->is_constant) {
  521. if (sub->datatype.kind == GDScriptParser::DataType::ENUM) {
  522. def_val = sub->get_datatype().to_string();
  523. } else if (sub->reduced) {
  524. const Variant::Type vt = sub->reduced_value.get_type();
  525. if (vt == Variant::Type::NIL || vt == Variant::Type::FLOAT || vt == Variant::Type::INT || vt == Variant::Type::STRING || vt == Variant::Type::STRING_NAME || vt == Variant::Type::BOOL || vt == Variant::Type::NODE_PATH) {
  526. def_val = sub->reduced_value.operator String();
  527. } else {
  528. def_val = sub->get_datatype().to_string() + sub->reduced_value.operator String();
  529. }
  530. }
  531. }
  532. } break;
  533. default:
  534. break;
  535. }
  536. arghint += " = " + def_val;
  537. }
  538. if (i == p_arg_idx) {
  539. arghint += String::chr(0xFFFF);
  540. }
  541. }
  542. arghint += ")";
  543. return arghint;
  544. }
  545. static void _get_directory_contents(EditorFileSystemDirectory *p_dir, Map<String, ScriptCodeCompletionOption> &r_list) {
  546. const String quote_style = EDITOR_GET("text_editor/completion/use_single_quotes") ? "'" : "\"";
  547. for (int i = 0; i < p_dir->get_file_count(); i++) {
  548. ScriptCodeCompletionOption option(p_dir->get_file_path(i), ScriptCodeCompletionOption::KIND_FILE_PATH);
  549. option.insert_text = option.display.quote(quote_style);
  550. r_list.insert(option.display, option);
  551. }
  552. for (int i = 0; i < p_dir->get_subdir_count(); i++) {
  553. _get_directory_contents(p_dir->get_subdir(i), r_list);
  554. }
  555. }
  556. static void _find_annotation_arguments(const GDScriptParser::AnnotationNode *p_annotation, int p_argument, const String p_quote_style, Map<String, ScriptCodeCompletionOption> &r_result) {
  557. if (p_annotation->name == SNAME("@export_range")) {
  558. if (p_argument == 3 || p_argument == 4) {
  559. // Slider hint.
  560. ScriptCodeCompletionOption slider1("or_greater", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
  561. slider1.insert_text = slider1.display.quote(p_quote_style);
  562. r_result.insert(slider1.display, slider1);
  563. ScriptCodeCompletionOption slider2("or_lesser", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
  564. slider2.insert_text = slider2.display.quote(p_quote_style);
  565. r_result.insert(slider2.display, slider2);
  566. }
  567. } else if (p_annotation->name == SNAME("@export_exp_easing")) {
  568. if (p_argument == 0 || p_argument == 1) {
  569. // Easing hint.
  570. ScriptCodeCompletionOption hint1("attenuation", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
  571. hint1.insert_text = hint1.display.quote(p_quote_style);
  572. r_result.insert(hint1.display, hint1);
  573. ScriptCodeCompletionOption hint2("inout", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
  574. hint2.insert_text = hint2.display.quote(p_quote_style);
  575. r_result.insert(hint2.display, hint2);
  576. }
  577. } else if (p_annotation->name == SNAME("@export_node_path")) {
  578. ScriptCodeCompletionOption node("Node", ScriptCodeCompletionOption::KIND_CLASS);
  579. r_result.insert(node.display, node);
  580. List<StringName> node_types;
  581. ClassDB::get_inheriters_from_class("Node", &node_types);
  582. for (const StringName &E : node_types) {
  583. if (!ClassDB::is_class_exposed(E)) {
  584. continue;
  585. }
  586. ScriptCodeCompletionOption option(E, ScriptCodeCompletionOption::KIND_CLASS);
  587. r_result.insert(option.display, option);
  588. }
  589. } else if (p_annotation->name == SNAME("@warning_ignore")) {
  590. for (int warning_code = 0; warning_code < GDScriptWarning::WARNING_MAX; warning_code++) {
  591. ScriptCodeCompletionOption warning(GDScriptWarning::get_name_from_code((GDScriptWarning::Code)warning_code).to_lower(), ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
  592. r_result.insert(warning.display, warning);
  593. }
  594. }
  595. }
  596. static void _list_available_types(bool p_inherit_only, GDScriptParser::CompletionContext &p_context, Map<String, ScriptCodeCompletionOption> &r_result) {
  597. List<StringName> native_types;
  598. ClassDB::get_class_list(&native_types);
  599. for (const StringName &E : native_types) {
  600. if (ClassDB::is_class_exposed(E) && !Engine::get_singleton()->has_singleton(E)) {
  601. ScriptCodeCompletionOption option(E, ScriptCodeCompletionOption::KIND_CLASS);
  602. r_result.insert(option.display, option);
  603. }
  604. }
  605. if (p_context.current_class) {
  606. if (!p_inherit_only && p_context.current_class->base_type.is_set()) {
  607. // Native enums from base class
  608. List<StringName> enums;
  609. ClassDB::get_enum_list(p_context.current_class->base_type.native_type, &enums);
  610. for (const StringName &E : enums) {
  611. ScriptCodeCompletionOption option(E, ScriptCodeCompletionOption::KIND_ENUM);
  612. r_result.insert(option.display, option);
  613. }
  614. }
  615. // Check current class for potential types
  616. const GDScriptParser::ClassNode *current = p_context.current_class;
  617. while (current) {
  618. for (int i = 0; i < current->members.size(); i++) {
  619. const GDScriptParser::ClassNode::Member &member = current->members[i];
  620. switch (member.type) {
  621. case GDScriptParser::ClassNode::Member::CLASS: {
  622. ScriptCodeCompletionOption option(member.m_class->identifier->name, ScriptCodeCompletionOption::KIND_CLASS);
  623. r_result.insert(option.display, option);
  624. } break;
  625. case GDScriptParser::ClassNode::Member::ENUM: {
  626. if (!p_inherit_only) {
  627. ScriptCodeCompletionOption option(member.m_enum->identifier->name, ScriptCodeCompletionOption::KIND_ENUM);
  628. r_result.insert(option.display, option);
  629. }
  630. } break;
  631. case GDScriptParser::ClassNode::Member::CONSTANT: {
  632. if (member.constant->get_datatype().is_meta_type && p_context.current_class->outer != nullptr) {
  633. ScriptCodeCompletionOption option(member.constant->identifier->name, ScriptCodeCompletionOption::KIND_CLASS);
  634. r_result.insert(option.display, option);
  635. }
  636. } break;
  637. default:
  638. break;
  639. }
  640. }
  641. current = current->outer;
  642. }
  643. }
  644. // Global scripts
  645. List<StringName> global_classes;
  646. ScriptServer::get_global_class_list(&global_classes);
  647. for (const StringName &E : global_classes) {
  648. ScriptCodeCompletionOption option(E, ScriptCodeCompletionOption::KIND_CLASS);
  649. r_result.insert(option.display, option);
  650. }
  651. // Autoload singletons
  652. OrderedHashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
  653. for (OrderedHashMap<StringName, ProjectSettings::AutoloadInfo>::Element E = autoloads.front(); E; E = E.next()) {
  654. const ProjectSettings::AutoloadInfo &info = E.get();
  655. if (!info.is_singleton || info.path.get_extension().to_lower() != "gd") {
  656. continue;
  657. }
  658. ScriptCodeCompletionOption option(info.name, ScriptCodeCompletionOption::KIND_CLASS);
  659. r_result.insert(option.display, option);
  660. }
  661. }
  662. static void _find_identifiers_in_suite(const GDScriptParser::SuiteNode *p_suite, Map<String, ScriptCodeCompletionOption> &r_result) {
  663. for (int i = 0; i < p_suite->locals.size(); i++) {
  664. ScriptCodeCompletionOption option;
  665. if (p_suite->locals[i].type == GDScriptParser::SuiteNode::Local::CONSTANT) {
  666. option = ScriptCodeCompletionOption(p_suite->locals[i].name, ScriptCodeCompletionOption::KIND_CONSTANT);
  667. option.default_value = p_suite->locals[i].constant->initializer->reduced_value;
  668. } else {
  669. option = ScriptCodeCompletionOption(p_suite->locals[i].name, ScriptCodeCompletionOption::KIND_VARIABLE);
  670. }
  671. r_result.insert(option.display, option);
  672. }
  673. if (p_suite->parent_block) {
  674. _find_identifiers_in_suite(p_suite->parent_block, r_result);
  675. }
  676. }
  677. static void _find_identifiers_in_base(const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Map<String, ScriptCodeCompletionOption> &r_result, int p_recursion_depth);
  678. static void _find_identifiers_in_class(const GDScriptParser::ClassNode *p_class, bool p_only_functions, bool p_static, bool p_parent_only, Map<String, ScriptCodeCompletionOption> &r_result, int p_recursion_depth) {
  679. ERR_FAIL_COND(p_recursion_depth > COMPLETION_RECURSION_LIMIT);
  680. if (!p_parent_only) {
  681. bool outer = false;
  682. const GDScriptParser::ClassNode *clss = p_class;
  683. while (clss) {
  684. for (int i = 0; i < clss->members.size(); i++) {
  685. const GDScriptParser::ClassNode::Member &member = clss->members[i];
  686. ScriptCodeCompletionOption option;
  687. switch (member.type) {
  688. case GDScriptParser::ClassNode::Member::VARIABLE:
  689. if (p_only_functions || outer || (p_static)) {
  690. continue;
  691. }
  692. option = ScriptCodeCompletionOption(member.variable->identifier->name, ScriptCodeCompletionOption::KIND_MEMBER);
  693. break;
  694. case GDScriptParser::ClassNode::Member::CONSTANT:
  695. if (p_only_functions) {
  696. continue;
  697. }
  698. if (r_result.has(member.constant->identifier->name)) {
  699. continue;
  700. }
  701. option = ScriptCodeCompletionOption(member.constant->identifier->name, ScriptCodeCompletionOption::KIND_CONSTANT);
  702. if (member.constant->initializer) {
  703. option.default_value = member.constant->initializer->reduced_value;
  704. }
  705. break;
  706. case GDScriptParser::ClassNode::Member::CLASS:
  707. if (p_only_functions) {
  708. continue;
  709. }
  710. option = ScriptCodeCompletionOption(member.m_class->identifier->name, ScriptCodeCompletionOption::KIND_CLASS);
  711. break;
  712. case GDScriptParser::ClassNode::Member::ENUM_VALUE:
  713. if (p_only_functions) {
  714. continue;
  715. }
  716. option = ScriptCodeCompletionOption(member.enum_value.identifier->name, ScriptCodeCompletionOption::KIND_CONSTANT);
  717. break;
  718. case GDScriptParser::ClassNode::Member::ENUM:
  719. if (p_only_functions) {
  720. continue;
  721. }
  722. option = ScriptCodeCompletionOption(member.m_enum->identifier->name, ScriptCodeCompletionOption::KIND_ENUM);
  723. break;
  724. case GDScriptParser::ClassNode::Member::FUNCTION:
  725. if (outer || (p_static && !member.function->is_static) || member.function->identifier->name.operator String().begins_with("@")) {
  726. continue;
  727. }
  728. option = ScriptCodeCompletionOption(member.function->identifier->name, ScriptCodeCompletionOption::KIND_FUNCTION);
  729. if (member.function->parameters.size() > 0) {
  730. option.insert_text += "(";
  731. } else {
  732. option.insert_text += "()";
  733. }
  734. break;
  735. case GDScriptParser::ClassNode::Member::SIGNAL:
  736. if (p_only_functions || outer) {
  737. continue;
  738. }
  739. option = ScriptCodeCompletionOption(member.signal->identifier->name, ScriptCodeCompletionOption::KIND_SIGNAL);
  740. break;
  741. case GDScriptParser::ClassNode::Member::UNDEFINED:
  742. break;
  743. }
  744. r_result.insert(option.display, option);
  745. }
  746. outer = true;
  747. clss = clss->outer;
  748. }
  749. }
  750. // Parents.
  751. GDScriptCompletionIdentifier base_type;
  752. base_type.type = p_class->base_type;
  753. base_type.type.is_meta_type = p_static;
  754. _find_identifiers_in_base(base_type, p_only_functions, r_result, p_recursion_depth + 1);
  755. }
  756. static void _find_identifiers_in_base(const GDScriptCompletionIdentifier &p_base, bool p_only_functions, Map<String, ScriptCodeCompletionOption> &r_result, int p_recursion_depth) {
  757. ERR_FAIL_COND(p_recursion_depth > COMPLETION_RECURSION_LIMIT);
  758. GDScriptParser::DataType base_type = p_base.type;
  759. bool _static = base_type.is_meta_type;
  760. if (_static && base_type.kind != GDScriptParser::DataType::BUILTIN) {
  761. ScriptCodeCompletionOption option("new", ScriptCodeCompletionOption::KIND_FUNCTION);
  762. option.insert_text += "(";
  763. r_result.insert(option.display, option);
  764. }
  765. while (!base_type.has_no_type()) {
  766. switch (base_type.kind) {
  767. case GDScriptParser::DataType::CLASS: {
  768. _find_identifiers_in_class(base_type.class_type, p_only_functions, _static, false, r_result, p_recursion_depth + 1);
  769. // This already finds all parent identifiers, so we are done.
  770. base_type = GDScriptParser::DataType();
  771. } break;
  772. case GDScriptParser::DataType::SCRIPT: {
  773. Ref<Script> scr = base_type.script_type;
  774. if (scr.is_valid()) {
  775. if (!p_only_functions) {
  776. if (!_static) {
  777. List<PropertyInfo> members;
  778. scr->get_script_property_list(&members);
  779. for (const PropertyInfo &E : members) {
  780. ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_MEMBER);
  781. r_result.insert(option.display, option);
  782. }
  783. }
  784. Map<StringName, Variant> constants;
  785. scr->get_constants(&constants);
  786. for (const KeyValue<StringName, Variant> &E : constants) {
  787. ScriptCodeCompletionOption option(E.key.operator String(), ScriptCodeCompletionOption::KIND_CONSTANT);
  788. r_result.insert(option.display, option);
  789. }
  790. List<MethodInfo> signals;
  791. scr->get_script_signal_list(&signals);
  792. for (const MethodInfo &E : signals) {
  793. ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_SIGNAL);
  794. r_result.insert(option.display, option);
  795. }
  796. }
  797. List<MethodInfo> methods;
  798. scr->get_script_method_list(&methods);
  799. for (const MethodInfo &E : methods) {
  800. if (E.name.begins_with("@")) {
  801. continue;
  802. }
  803. ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_FUNCTION);
  804. if (E.arguments.size()) {
  805. option.insert_text += "(";
  806. } else {
  807. option.insert_text += "()";
  808. }
  809. r_result.insert(option.display, option);
  810. }
  811. Ref<Script> base_script = scr->get_base_script();
  812. if (base_script.is_valid()) {
  813. base_type.script_type = base_script;
  814. } else {
  815. base_type.kind = GDScriptParser::DataType::NATIVE;
  816. base_type.native_type = scr->get_instance_base_type();
  817. }
  818. } else {
  819. return;
  820. }
  821. } break;
  822. case GDScriptParser::DataType::NATIVE: {
  823. StringName type = base_type.native_type;
  824. if (!ClassDB::class_exists(type)) {
  825. return;
  826. }
  827. if (!p_only_functions) {
  828. List<String> constants;
  829. ClassDB::get_integer_constant_list(type, &constants);
  830. for (const String &E : constants) {
  831. ScriptCodeCompletionOption option(E, ScriptCodeCompletionOption::KIND_CONSTANT);
  832. r_result.insert(option.display, option);
  833. }
  834. if (!_static || Engine::get_singleton()->has_singleton(type)) {
  835. List<PropertyInfo> pinfo;
  836. ClassDB::get_property_list(type, &pinfo);
  837. for (const PropertyInfo &E : pinfo) {
  838. if (E.usage & (PROPERTY_USAGE_GROUP | PROPERTY_USAGE_CATEGORY)) {
  839. continue;
  840. }
  841. if (E.name.contains("/")) {
  842. continue;
  843. }
  844. ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_MEMBER);
  845. r_result.insert(option.display, option);
  846. }
  847. }
  848. }
  849. if (!_static || Engine::get_singleton()->has_singleton(type)) {
  850. List<MethodInfo> methods;
  851. ClassDB::get_method_list(type, &methods, false, true);
  852. for (const MethodInfo &E : methods) {
  853. if (E.name.begins_with("_")) {
  854. continue;
  855. }
  856. ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_FUNCTION);
  857. if (E.arguments.size()) {
  858. option.insert_text += "(";
  859. } else {
  860. option.insert_text += "()";
  861. }
  862. r_result.insert(option.display, option);
  863. }
  864. }
  865. return;
  866. } break;
  867. case GDScriptParser::DataType::BUILTIN: {
  868. Callable::CallError err;
  869. Variant tmp;
  870. Variant::construct(base_type.builtin_type, tmp, nullptr, 0, err);
  871. if (err.error != Callable::CallError::CALL_OK) {
  872. return;
  873. }
  874. if (!p_only_functions) {
  875. List<PropertyInfo> members;
  876. if (p_base.value.get_type() != Variant::NIL) {
  877. p_base.value.get_property_list(&members);
  878. } else {
  879. tmp.get_property_list(&members);
  880. }
  881. for (const PropertyInfo &E : members) {
  882. if (!String(E.name).contains("/")) {
  883. ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_MEMBER);
  884. r_result.insert(option.display, option);
  885. }
  886. }
  887. }
  888. List<MethodInfo> methods;
  889. tmp.get_method_list(&methods);
  890. for (const MethodInfo &E : methods) {
  891. ScriptCodeCompletionOption option(E.name, ScriptCodeCompletionOption::KIND_FUNCTION);
  892. if (E.arguments.size()) {
  893. option.insert_text += "(";
  894. } else {
  895. option.insert_text += "()";
  896. }
  897. r_result.insert(option.display, option);
  898. }
  899. return;
  900. } break;
  901. default: {
  902. return;
  903. } break;
  904. }
  905. }
  906. }
  907. static void _find_identifiers(GDScriptParser::CompletionContext &p_context, bool p_only_functions, Map<String, ScriptCodeCompletionOption> &r_result, int p_recursion_depth) {
  908. if (!p_only_functions && p_context.current_suite) {
  909. // This includes function parameters, since they are also locals.
  910. _find_identifiers_in_suite(p_context.current_suite, r_result);
  911. }
  912. if (p_context.current_class) {
  913. _find_identifiers_in_class(p_context.current_class, p_only_functions, (!p_context.current_function || p_context.current_function->is_static), false, r_result, p_recursion_depth + 1);
  914. }
  915. List<StringName> functions;
  916. GDScriptUtilityFunctions::get_function_list(&functions);
  917. for (const StringName &E : functions) {
  918. MethodInfo function = GDScriptUtilityFunctions::get_function_info(E);
  919. ScriptCodeCompletionOption option(String(E), ScriptCodeCompletionOption::KIND_FUNCTION);
  920. if (function.arguments.size() || (function.flags & METHOD_FLAG_VARARG)) {
  921. option.insert_text += "(";
  922. } else {
  923. option.insert_text += "()";
  924. }
  925. r_result.insert(option.display, option);
  926. }
  927. if (p_only_functions) {
  928. return;
  929. }
  930. static const char *_type_names[Variant::VARIANT_MAX] = {
  931. "null", "bool", "int", "float", "String", "StringName", "Vector2", "Vector2i", "Rect2", "Rect2i", "Vector3", "Vector3i", "Transform2D", "Plane", "Quaternion", "AABB", "Basis", "Transform3D",
  932. "Color", "NodePath", "RID", "Signal", "Callable", "Object", "Dictionary", "Array", "PackedByteArray", "PackedInt32Array", "PackedInt64Array", "PackedFloat32Array", "PackedFloat64Array", "PackedStringArray",
  933. "PackedVector2Array", "PackedVector3Array", "PackedColorArray"
  934. };
  935. static_assert((sizeof(_type_names) / sizeof(*_type_names)) == Variant::VARIANT_MAX, "Completion for builtin types is incomplete");
  936. for (int i = 0; i < Variant::VARIANT_MAX; i++) {
  937. ScriptCodeCompletionOption option(_type_names[i], ScriptCodeCompletionOption::KIND_CLASS);
  938. r_result.insert(option.display, option);
  939. }
  940. static const char *_keywords[] = {
  941. "false", "PI", "TAU", "INF", "NAN", "self", "true", "breakpoint", "tool", "super",
  942. "break", "continue", "pass", "return",
  943. nullptr
  944. };
  945. const char **kw = _keywords;
  946. while (*kw) {
  947. ScriptCodeCompletionOption option(*kw, ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
  948. r_result.insert(option.display, option);
  949. kw++;
  950. }
  951. static const char *_keywords_with_space[] = {
  952. "and", "in", "not", "or", "as", "class", "extends", "is", "func", "signal", "await",
  953. "const", "enum", "static", "var", "if", "elif", "else", "for", "match", "while",
  954. nullptr
  955. };
  956. const char **kws = _keywords_with_space;
  957. while (*kws) {
  958. ScriptCodeCompletionOption option(*kws, ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
  959. option.insert_text += " ";
  960. r_result.insert(option.display, option);
  961. kws++;
  962. }
  963. static const char *_keywords_with_args[] = {
  964. "assert", "preload",
  965. nullptr
  966. };
  967. const char **kwa = _keywords_with_args;
  968. while (*kwa) {
  969. ScriptCodeCompletionOption option(*kwa, ScriptCodeCompletionOption::KIND_FUNCTION);
  970. option.insert_text += "(";
  971. r_result.insert(option.display, option);
  972. kwa++;
  973. }
  974. List<StringName> utility_func_names;
  975. Variant::get_utility_function_list(&utility_func_names);
  976. for (List<StringName>::Element *E = utility_func_names.front(); E; E = E->next()) {
  977. ScriptCodeCompletionOption option(E->get(), ScriptCodeCompletionOption::KIND_FUNCTION);
  978. option.insert_text += "(";
  979. r_result.insert(option.display, option);
  980. }
  981. OrderedHashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
  982. for (OrderedHashMap<StringName, ProjectSettings::AutoloadInfo>::Element E = autoloads.front(); E; E = E.next()) {
  983. if (!E.value().is_singleton) {
  984. continue;
  985. }
  986. ScriptCodeCompletionOption option(E.key(), ScriptCodeCompletionOption::KIND_CONSTANT);
  987. r_result.insert(option.display, option);
  988. }
  989. // Native classes and global constants.
  990. for (const KeyValue<StringName, int> &E : GDScriptLanguage::get_singleton()->get_global_map()) {
  991. ScriptCodeCompletionOption option;
  992. if (ClassDB::class_exists(E.key) || Engine::get_singleton()->has_singleton(E.key)) {
  993. option = ScriptCodeCompletionOption(E.key.operator String(), ScriptCodeCompletionOption::KIND_CLASS);
  994. } else {
  995. option = ScriptCodeCompletionOption(E.key.operator String(), ScriptCodeCompletionOption::KIND_CONSTANT);
  996. }
  997. r_result.insert(option.display, option);
  998. }
  999. }
  1000. static GDScriptCompletionIdentifier _type_from_variant(const Variant &p_value) {
  1001. GDScriptCompletionIdentifier ci;
  1002. ci.value = p_value;
  1003. ci.type.is_constant = true;
  1004. ci.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1005. ci.type.kind = GDScriptParser::DataType::BUILTIN;
  1006. ci.type.builtin_type = p_value.get_type();
  1007. if (ci.type.builtin_type == Variant::OBJECT) {
  1008. Object *obj = p_value.operator Object *();
  1009. if (!obj) {
  1010. return ci;
  1011. }
  1012. ci.type.native_type = obj->get_class_name();
  1013. Ref<Script> scr = p_value;
  1014. if (scr.is_valid()) {
  1015. ci.type.is_meta_type = true;
  1016. } else {
  1017. ci.type.is_meta_type = false;
  1018. scr = obj->get_script();
  1019. }
  1020. if (scr.is_valid()) {
  1021. ci.type.script_type = scr;
  1022. ci.type.kind = GDScriptParser::DataType::SCRIPT;
  1023. ci.type.native_type = scr->get_instance_base_type();
  1024. } else {
  1025. ci.type.kind = GDScriptParser::DataType::NATIVE;
  1026. }
  1027. }
  1028. return ci;
  1029. }
  1030. static GDScriptCompletionIdentifier _type_from_property(const PropertyInfo &p_property) {
  1031. GDScriptCompletionIdentifier ci;
  1032. if (p_property.type == Variant::NIL) {
  1033. // Variant
  1034. return ci;
  1035. }
  1036. if (p_property.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
  1037. ci.enumeration = p_property.class_name;
  1038. }
  1039. ci.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1040. ci.type.builtin_type = p_property.type;
  1041. if (p_property.type == Variant::OBJECT) {
  1042. ci.type.kind = GDScriptParser::DataType::NATIVE;
  1043. ci.type.native_type = p_property.class_name == StringName() ? "Object" : p_property.class_name;
  1044. } else {
  1045. ci.type.kind = GDScriptParser::DataType::BUILTIN;
  1046. }
  1047. return ci;
  1048. }
  1049. static bool _guess_identifier_type(GDScriptParser::CompletionContext &p_context, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type);
  1050. static bool _guess_identifier_type_from_base(GDScriptParser::CompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type);
  1051. static bool _guess_method_return_type_from_base(GDScriptParser::CompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, GDScriptCompletionIdentifier &r_type);
  1052. static bool _is_expression_named_identifier(const GDScriptParser::ExpressionNode *p_expression, const StringName &p_name) {
  1053. if (p_expression) {
  1054. switch (p_expression->type) {
  1055. case GDScriptParser::Node::IDENTIFIER: {
  1056. const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(p_expression);
  1057. if (id->name == p_name) {
  1058. return true;
  1059. }
  1060. } break;
  1061. case GDScriptParser::Node::CAST: {
  1062. const GDScriptParser::CastNode *cn = static_cast<const GDScriptParser::CastNode *>(p_expression);
  1063. return _is_expression_named_identifier(cn->operand, p_name);
  1064. } break;
  1065. default:
  1066. break;
  1067. }
  1068. }
  1069. return false;
  1070. }
  1071. static bool _guess_expression_type(GDScriptParser::CompletionContext &p_context, const GDScriptParser::ExpressionNode *p_expression, GDScriptCompletionIdentifier &r_type) {
  1072. bool found = false;
  1073. if (p_expression == nullptr) {
  1074. return false;
  1075. }
  1076. if (p_expression->is_constant) {
  1077. // Already has a value, so just use that.
  1078. r_type = _type_from_variant(p_expression->reduced_value);
  1079. found = true;
  1080. } else {
  1081. switch (p_expression->type) {
  1082. case GDScriptParser::Node::LITERAL: {
  1083. const GDScriptParser::LiteralNode *literal = static_cast<const GDScriptParser::LiteralNode *>(p_expression);
  1084. r_type = _type_from_variant(literal->value);
  1085. found = true;
  1086. } break;
  1087. case GDScriptParser::Node::SELF: {
  1088. if (p_context.current_class) {
  1089. r_type.type.kind = GDScriptParser::DataType::CLASS;
  1090. r_type.type.type_source = GDScriptParser::DataType::INFERRED;
  1091. r_type.type.is_constant = true;
  1092. r_type.type.class_type = p_context.current_class;
  1093. r_type.value = p_context.base;
  1094. found = true;
  1095. }
  1096. } break;
  1097. case GDScriptParser::Node::IDENTIFIER: {
  1098. const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(p_expression);
  1099. found = _guess_identifier_type(p_context, id->name, r_type);
  1100. } break;
  1101. case GDScriptParser::Node::DICTIONARY: {
  1102. // Try to recreate the dictionary.
  1103. const GDScriptParser::DictionaryNode *dn = static_cast<const GDScriptParser::DictionaryNode *>(p_expression);
  1104. Dictionary d;
  1105. bool full = true;
  1106. for (int i = 0; i < dn->elements.size(); i++) {
  1107. GDScriptCompletionIdentifier key;
  1108. if (_guess_expression_type(p_context, dn->elements[i].key, key)) {
  1109. if (!key.type.is_constant) {
  1110. full = false;
  1111. break;
  1112. }
  1113. GDScriptCompletionIdentifier value;
  1114. if (_guess_expression_type(p_context, dn->elements[i].value, value)) {
  1115. if (!value.type.is_constant) {
  1116. full = false;
  1117. break;
  1118. }
  1119. d[key.value] = value.value;
  1120. } else {
  1121. full = false;
  1122. break;
  1123. }
  1124. } else {
  1125. full = false;
  1126. break;
  1127. }
  1128. }
  1129. if (full) {
  1130. r_type.value = d;
  1131. r_type.type.is_constant = true;
  1132. }
  1133. r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1134. r_type.type.kind = GDScriptParser::DataType::BUILTIN;
  1135. r_type.type.builtin_type = Variant::DICTIONARY;
  1136. found = true;
  1137. } break;
  1138. case GDScriptParser::Node::ARRAY: {
  1139. // Try to recreate the array
  1140. const GDScriptParser::ArrayNode *an = static_cast<const GDScriptParser::ArrayNode *>(p_expression);
  1141. Array a;
  1142. bool full = true;
  1143. a.resize(an->elements.size());
  1144. for (int i = 0; i < an->elements.size(); i++) {
  1145. GDScriptCompletionIdentifier value;
  1146. if (_guess_expression_type(p_context, an->elements[i], value)) {
  1147. if (value.type.is_constant) {
  1148. a[i] = value.value;
  1149. } else {
  1150. full = false;
  1151. break;
  1152. }
  1153. } else {
  1154. full = false;
  1155. break;
  1156. }
  1157. }
  1158. if (full) {
  1159. // If not fully constant, setting this value is detrimental to the inference.
  1160. r_type.value = a;
  1161. }
  1162. r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1163. r_type.type.kind = GDScriptParser::DataType::BUILTIN;
  1164. r_type.type.builtin_type = Variant::ARRAY;
  1165. found = true;
  1166. } break;
  1167. case GDScriptParser::Node::CAST: {
  1168. const GDScriptParser::CastNode *cn = static_cast<const GDScriptParser::CastNode *>(p_expression);
  1169. GDScriptCompletionIdentifier value;
  1170. if (_guess_expression_type(p_context, cn->operand, r_type)) {
  1171. r_type.type = cn->get_datatype();
  1172. found = true;
  1173. }
  1174. } break;
  1175. case GDScriptParser::Node::CALL: {
  1176. const GDScriptParser::CallNode *call = static_cast<const GDScriptParser::CallNode *>(p_expression);
  1177. if (GDScriptParser::get_builtin_type(call->function_name) < Variant::VARIANT_MAX) {
  1178. r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1179. r_type.type.kind = GDScriptParser::DataType::BUILTIN;
  1180. r_type.type.builtin_type = GDScriptParser::get_builtin_type(call->function_name);
  1181. found = true;
  1182. break;
  1183. } else if (GDScriptUtilityFunctions::function_exists(call->function_name)) {
  1184. MethodInfo mi = GDScriptUtilityFunctions::get_function_info(call->function_name);
  1185. r_type = _type_from_property(mi.return_val);
  1186. found = true;
  1187. break;
  1188. } else {
  1189. GDScriptParser::CompletionContext c = p_context;
  1190. c.current_line = call->start_line;
  1191. GDScriptParser::Node::Type callee_type = call->get_callee_type();
  1192. GDScriptCompletionIdentifier base;
  1193. if (callee_type == GDScriptParser::Node::IDENTIFIER || call->is_super) {
  1194. // Simple call, so base is 'self'.
  1195. if (p_context.current_class) {
  1196. base.type.kind = GDScriptParser::DataType::CLASS;
  1197. base.type.type_source = GDScriptParser::DataType::INFERRED;
  1198. base.type.is_constant = true;
  1199. base.type.class_type = p_context.current_class;
  1200. base.value = p_context.base;
  1201. } else {
  1202. break;
  1203. }
  1204. } else if (callee_type == GDScriptParser::Node::SUBSCRIPT && static_cast<const GDScriptParser::SubscriptNode *>(call->callee)->is_attribute) {
  1205. if (!_guess_expression_type(c, static_cast<const GDScriptParser::SubscriptNode *>(call->callee)->base, base)) {
  1206. found = false;
  1207. break;
  1208. }
  1209. } else {
  1210. break;
  1211. }
  1212. // Try call if constant methods with constant arguments
  1213. if (base.type.is_constant && base.value.get_type() == Variant::OBJECT) {
  1214. GDScriptParser::DataType native_type = base.type;
  1215. while (native_type.kind == GDScriptParser::DataType::CLASS) {
  1216. native_type = native_type.class_type->base_type;
  1217. }
  1218. while (native_type.kind == GDScriptParser::DataType::SCRIPT) {
  1219. if (native_type.script_type.is_valid()) {
  1220. Ref<Script> parent = native_type.script_type->get_base_script();
  1221. if (parent.is_valid()) {
  1222. native_type.script_type = parent;
  1223. } else {
  1224. native_type.kind = GDScriptParser::DataType::NATIVE;
  1225. native_type.native_type = native_type.script_type->get_instance_base_type();
  1226. if (!ClassDB::class_exists(native_type.native_type)) {
  1227. native_type.kind = GDScriptParser::DataType::UNRESOLVED;
  1228. }
  1229. }
  1230. }
  1231. }
  1232. if (native_type.kind == GDScriptParser::DataType::NATIVE) {
  1233. MethodBind *mb = ClassDB::get_method(native_type.native_type, call->function_name);
  1234. if (mb && mb->is_const()) {
  1235. bool all_is_const = true;
  1236. Vector<Variant> args;
  1237. GDScriptParser::CompletionContext c2 = p_context;
  1238. c2.current_line = call->start_line;
  1239. for (int i = 0; all_is_const && i < call->arguments.size(); i++) {
  1240. GDScriptCompletionIdentifier arg;
  1241. if (!call->arguments[i]->is_constant) {
  1242. all_is_const = false;
  1243. }
  1244. }
  1245. Object *baseptr = base.value;
  1246. if (all_is_const && call->function_name == SNAME("get_node") && ClassDB::is_parent_class(native_type.native_type, SNAME("Node")) && args.size()) {
  1247. String arg1 = args[0];
  1248. if (arg1.begins_with("/root/")) {
  1249. String which = arg1.get_slice("/", 2);
  1250. if (!which.is_empty()) {
  1251. // Try singletons first
  1252. if (GDScriptLanguage::get_singleton()->get_named_globals_map().has(which)) {
  1253. r_type = _type_from_variant(GDScriptLanguage::get_singleton()->get_named_globals_map()[which]);
  1254. found = true;
  1255. } else {
  1256. OrderedHashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
  1257. for (OrderedHashMap<StringName, ProjectSettings::AutoloadInfo>::Element E = autoloads.front(); E; E = E.next()) {
  1258. String name = E.key();
  1259. if (name == which) {
  1260. String script = E.value().path;
  1261. if (!script.begins_with("res://")) {
  1262. script = "res://" + script;
  1263. }
  1264. if (!script.ends_with(".gd")) {
  1265. // not a script, try find the script anyway,
  1266. // may have some success
  1267. script = script.get_basename() + ".gd";
  1268. }
  1269. if (FileAccess::exists(script)) {
  1270. Error err = OK;
  1271. Ref<GDScriptParserRef> parser = GDScriptCache::get_parser(script, GDScriptParserRef::INTERFACE_SOLVED, err);
  1272. if (err == OK) {
  1273. r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1274. r_type.type.script_path = script;
  1275. r_type.type.class_type = parser->get_parser()->get_tree();
  1276. r_type.type.is_constant = false;
  1277. r_type.type.kind = GDScriptParser::DataType::CLASS;
  1278. r_type.value = Variant();
  1279. p_context.dependent_parsers.push_back(parser);
  1280. found = true;
  1281. }
  1282. }
  1283. break;
  1284. }
  1285. }
  1286. }
  1287. }
  1288. }
  1289. }
  1290. if (!found && all_is_const && baseptr) {
  1291. Vector<const Variant *> argptr;
  1292. for (int i = 0; i < args.size(); i++) {
  1293. argptr.push_back(&args[i]);
  1294. }
  1295. Callable::CallError ce;
  1296. Variant ret = mb->call(baseptr, (const Variant **)argptr.ptr(), argptr.size(), ce);
  1297. if (ce.error == Callable::CallError::CALL_OK && ret.get_type() != Variant::NIL) {
  1298. if (ret.get_type() != Variant::OBJECT || ret.operator Object *() != nullptr) {
  1299. r_type = _type_from_variant(ret);
  1300. found = true;
  1301. }
  1302. }
  1303. }
  1304. }
  1305. }
  1306. }
  1307. if (!found) {
  1308. found = _guess_method_return_type_from_base(c, base, call->function_name, r_type);
  1309. }
  1310. }
  1311. } break;
  1312. case GDScriptParser::Node::SUBSCRIPT: {
  1313. const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(p_expression);
  1314. if (subscript->is_attribute) {
  1315. GDScriptParser::CompletionContext c = p_context;
  1316. c.current_line = subscript->start_line;
  1317. GDScriptCompletionIdentifier base;
  1318. if (!_guess_expression_type(c, subscript->base, base)) {
  1319. found = false;
  1320. break;
  1321. }
  1322. if (base.value.get_type() == Variant::DICTIONARY && base.value.operator Dictionary().has(String(subscript->attribute->name))) {
  1323. Variant value = base.value.operator Dictionary()[String(subscript->attribute->name)];
  1324. r_type = _type_from_variant(value);
  1325. found = true;
  1326. break;
  1327. }
  1328. const GDScriptParser::DictionaryNode *dn = nullptr;
  1329. if (subscript->base->type == GDScriptParser::Node::DICTIONARY) {
  1330. dn = static_cast<const GDScriptParser::DictionaryNode *>(subscript->base);
  1331. } else if (base.assigned_expression && base.assigned_expression->type == GDScriptParser::Node::DICTIONARY) {
  1332. dn = static_cast<const GDScriptParser::DictionaryNode *>(base.assigned_expression);
  1333. }
  1334. if (dn) {
  1335. for (int i = 0; i < dn->elements.size(); i++) {
  1336. GDScriptCompletionIdentifier key;
  1337. if (!_guess_expression_type(c, dn->elements[i].key, key)) {
  1338. continue;
  1339. }
  1340. if (key.value == String(subscript->attribute->name)) {
  1341. r_type.assigned_expression = dn->elements[i].value;
  1342. found = _guess_expression_type(c, dn->elements[i].value, r_type);
  1343. break;
  1344. }
  1345. }
  1346. }
  1347. if (!found) {
  1348. found = _guess_identifier_type_from_base(c, base, subscript->attribute->name, r_type);
  1349. }
  1350. } else {
  1351. if (subscript->index == nullptr) {
  1352. found = false;
  1353. break;
  1354. }
  1355. GDScriptParser::CompletionContext c = p_context;
  1356. c.current_line = subscript->start_line;
  1357. GDScriptCompletionIdentifier base;
  1358. if (!_guess_expression_type(c, subscript->base, base)) {
  1359. found = false;
  1360. break;
  1361. }
  1362. GDScriptCompletionIdentifier index;
  1363. if (!_guess_expression_type(c, subscript->index, index)) {
  1364. found = false;
  1365. break;
  1366. }
  1367. if (base.value.in(index.value)) {
  1368. Variant value = base.value.get(index.value);
  1369. r_type = _type_from_variant(value);
  1370. found = true;
  1371. break;
  1372. }
  1373. // Look if it is a dictionary node.
  1374. const GDScriptParser::DictionaryNode *dn = nullptr;
  1375. if (subscript->base->type == GDScriptParser::Node::DICTIONARY) {
  1376. dn = static_cast<const GDScriptParser::DictionaryNode *>(subscript->base);
  1377. } else if (base.assigned_expression && base.assigned_expression->type == GDScriptParser::Node::DICTIONARY) {
  1378. dn = static_cast<const GDScriptParser::DictionaryNode *>(base.assigned_expression);
  1379. }
  1380. if (dn) {
  1381. for (int i = 0; i < dn->elements.size(); i++) {
  1382. GDScriptCompletionIdentifier key;
  1383. if (!_guess_expression_type(c, dn->elements[i].key, key)) {
  1384. continue;
  1385. }
  1386. if (key.value == index.value) {
  1387. r_type.assigned_expression = dn->elements[i].value;
  1388. found = _guess_expression_type(p_context, dn->elements[i].value, r_type);
  1389. break;
  1390. }
  1391. }
  1392. }
  1393. // Look if it is an array node.
  1394. if (!found && index.value.is_num()) {
  1395. int idx = index.value;
  1396. const GDScriptParser::ArrayNode *an = nullptr;
  1397. if (subscript->base->type == GDScriptParser::Node::ARRAY) {
  1398. an = static_cast<const GDScriptParser::ArrayNode *>(subscript->base);
  1399. } else if (base.assigned_expression && base.assigned_expression->type == GDScriptParser::Node::ARRAY) {
  1400. an = static_cast<const GDScriptParser::ArrayNode *>(base.assigned_expression);
  1401. }
  1402. if (an && idx >= 0 && an->elements.size() > idx) {
  1403. r_type.assigned_expression = an->elements[idx];
  1404. found = _guess_expression_type(c, an->elements[idx], r_type);
  1405. break;
  1406. }
  1407. }
  1408. // Look for valid indexing in other types
  1409. if (!found && (index.value.get_type() == Variant::STRING || index.value.get_type() == Variant::NODE_PATH)) {
  1410. StringName id = index.value;
  1411. found = _guess_identifier_type_from_base(c, base, id, r_type);
  1412. } else if (!found && index.type.kind == GDScriptParser::DataType::BUILTIN) {
  1413. Callable::CallError err;
  1414. Variant base_val;
  1415. Variant::construct(base.type.builtin_type, base_val, nullptr, 0, err);
  1416. bool valid = false;
  1417. Variant res = base_val.get(index.value, &valid);
  1418. if (valid) {
  1419. r_type = _type_from_variant(res);
  1420. r_type.value = Variant();
  1421. r_type.type.is_constant = false;
  1422. found = true;
  1423. }
  1424. }
  1425. }
  1426. } break;
  1427. case GDScriptParser::Node::BINARY_OPERATOR: {
  1428. const GDScriptParser::BinaryOpNode *op = static_cast<const GDScriptParser::BinaryOpNode *>(p_expression);
  1429. if (op->variant_op == Variant::OP_MAX) {
  1430. break;
  1431. }
  1432. GDScriptParser::CompletionContext context = p_context;
  1433. context.current_line = op->start_line;
  1434. GDScriptCompletionIdentifier p1;
  1435. GDScriptCompletionIdentifier p2;
  1436. if (!_guess_expression_type(context, op->left_operand, p1)) {
  1437. found = false;
  1438. break;
  1439. }
  1440. if (!_guess_expression_type(context, op->right_operand, p2)) {
  1441. found = false;
  1442. break;
  1443. }
  1444. Callable::CallError ce;
  1445. bool v1_use_value = p1.value.get_type() != Variant::NIL && p1.value.get_type() != Variant::OBJECT;
  1446. Variant d1;
  1447. Variant::construct(p1.type.builtin_type, d1, nullptr, 0, ce);
  1448. Variant d2;
  1449. Variant::construct(p2.type.builtin_type, d2, nullptr, 0, ce);
  1450. Variant v1 = (v1_use_value) ? p1.value : d1;
  1451. bool v2_use_value = p2.value.get_type() != Variant::NIL && p2.value.get_type() != Variant::OBJECT;
  1452. Variant v2 = (v2_use_value) ? p2.value : d2;
  1453. // avoid potential invalid ops
  1454. if ((op->variant_op == Variant::OP_DIVIDE || op->variant_op == Variant::OP_MODULE) && v2.get_type() == Variant::INT) {
  1455. v2 = 1;
  1456. v2_use_value = false;
  1457. }
  1458. if (op->variant_op == Variant::OP_DIVIDE && v2.get_type() == Variant::FLOAT) {
  1459. v2 = 1.0;
  1460. v2_use_value = false;
  1461. }
  1462. Variant res;
  1463. bool valid;
  1464. Variant::evaluate(op->variant_op, v1, v2, res, valid);
  1465. if (!valid) {
  1466. found = false;
  1467. break;
  1468. }
  1469. r_type = _type_from_variant(res);
  1470. if (!v1_use_value || !v2_use_value) {
  1471. r_type.value = Variant();
  1472. r_type.type.is_constant = false;
  1473. }
  1474. found = true;
  1475. } break;
  1476. default:
  1477. break;
  1478. }
  1479. }
  1480. // It may have found a null, but that's never useful
  1481. if (found && r_type.type.kind == GDScriptParser::DataType::BUILTIN && r_type.type.builtin_type == Variant::NIL) {
  1482. found = false;
  1483. }
  1484. // Check type hint last. For collections we want chance to get the actual value first
  1485. // This way we can detect types from the content of dictionaries and arrays
  1486. if (!found && p_expression->get_datatype().is_hard_type()) {
  1487. r_type.type = p_expression->get_datatype();
  1488. if (!r_type.assigned_expression) {
  1489. r_type.assigned_expression = p_expression;
  1490. }
  1491. found = true;
  1492. }
  1493. return found;
  1494. }
  1495. static bool _guess_identifier_type(GDScriptParser::CompletionContext &p_context, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type) {
  1496. // Look in blocks first.
  1497. int last_assign_line = -1;
  1498. const GDScriptParser::ExpressionNode *last_assigned_expression = nullptr;
  1499. GDScriptParser::DataType id_type;
  1500. GDScriptParser::SuiteNode *suite = p_context.current_suite;
  1501. bool is_function_parameter = false;
  1502. if (suite) {
  1503. if (suite->has_local(p_identifier)) {
  1504. const GDScriptParser::SuiteNode::Local &local = suite->get_local(p_identifier);
  1505. id_type = local.get_datatype();
  1506. // Check initializer as the first assignment.
  1507. switch (local.type) {
  1508. case GDScriptParser::SuiteNode::Local::VARIABLE:
  1509. if (local.variable->initializer) {
  1510. last_assign_line = local.variable->initializer->end_line;
  1511. last_assigned_expression = local.variable->initializer;
  1512. }
  1513. break;
  1514. case GDScriptParser::SuiteNode::Local::CONSTANT:
  1515. if (local.constant->initializer) {
  1516. last_assign_line = local.constant->initializer->end_line;
  1517. last_assigned_expression = local.constant->initializer;
  1518. }
  1519. break;
  1520. case GDScriptParser::SuiteNode::Local::PARAMETER:
  1521. if (local.parameter->default_value) {
  1522. last_assign_line = local.parameter->default_value->end_line;
  1523. last_assigned_expression = local.parameter->default_value;
  1524. }
  1525. is_function_parameter = true;
  1526. break;
  1527. default:
  1528. break;
  1529. }
  1530. }
  1531. }
  1532. while (suite) {
  1533. for (int i = 0; i < suite->statements.size(); i++) {
  1534. if (suite->statements[i]->start_line > p_context.current_line) {
  1535. break;
  1536. }
  1537. switch (suite->statements[i]->type) {
  1538. case GDScriptParser::Node::ASSIGNMENT: {
  1539. const GDScriptParser::AssignmentNode *assign = static_cast<const GDScriptParser::AssignmentNode *>(suite->statements[i]);
  1540. if (assign->end_line > last_assign_line && assign->assignee && assign->assigned_value && assign->assignee->type == GDScriptParser::Node::IDENTIFIER) {
  1541. const GDScriptParser::IdentifierNode *id = static_cast<const GDScriptParser::IdentifierNode *>(assign->assignee);
  1542. if (id->name == p_identifier) {
  1543. last_assign_line = assign->assigned_value->end_line;
  1544. last_assigned_expression = assign->assigned_value;
  1545. }
  1546. }
  1547. } break;
  1548. default:
  1549. // TODO: Check sub blocks (control flow statements) as they might also reassign stuff.
  1550. break;
  1551. }
  1552. }
  1553. if (suite->parent_if && suite->parent_if->condition && suite->parent_if->condition->type == GDScriptParser::Node::BINARY_OPERATOR && static_cast<const GDScriptParser::BinaryOpNode *>(suite->parent_if->condition)->operation == GDScriptParser::BinaryOpNode::OP_TYPE_TEST) {
  1554. // Operator `is` used, check if identifier is in there! this helps resolve in blocks that are (if (identifier is value)): which are very common..
  1555. // Super dirty hack, but very useful.
  1556. // Credit: Zylann.
  1557. // TODO: this could be hacked to detect ANDed conditions too...
  1558. const GDScriptParser::BinaryOpNode *op = static_cast<const GDScriptParser::BinaryOpNode *>(suite->parent_if->condition);
  1559. if (op->left_operand && op->right_operand && op->left_operand->type == GDScriptParser::Node::IDENTIFIER && static_cast<const GDScriptParser::IdentifierNode *>(op->left_operand)->name == p_identifier) {
  1560. // Bingo.
  1561. GDScriptParser::CompletionContext c = p_context;
  1562. c.current_line = op->left_operand->start_line;
  1563. c.current_suite = suite;
  1564. GDScriptCompletionIdentifier is_type;
  1565. if (_guess_expression_type(c, op->right_operand, is_type)) {
  1566. id_type = is_type.type;
  1567. id_type.is_meta_type = false;
  1568. if (last_assign_line < c.current_line) {
  1569. // Override last assignment.
  1570. last_assign_line = c.current_line;
  1571. last_assigned_expression = nullptr;
  1572. }
  1573. }
  1574. }
  1575. }
  1576. suite = suite->parent_block;
  1577. }
  1578. if (last_assigned_expression && last_assign_line != p_context.current_line) {
  1579. GDScriptParser::CompletionContext c = p_context;
  1580. c.current_line = last_assign_line;
  1581. r_type.assigned_expression = last_assigned_expression;
  1582. if (_guess_expression_type(c, last_assigned_expression, r_type)) {
  1583. return true;
  1584. }
  1585. }
  1586. if (is_function_parameter && p_context.current_function && p_context.current_function->source_lambda == nullptr && p_context.current_class) {
  1587. // Check if it's override of native function, then we can assume the type from the signature.
  1588. GDScriptParser::DataType base_type = p_context.current_class->base_type;
  1589. while (base_type.is_set()) {
  1590. switch (base_type.kind) {
  1591. case GDScriptParser::DataType::CLASS:
  1592. if (base_type.class_type->has_function(p_context.current_function->identifier->name)) {
  1593. GDScriptParser::FunctionNode *parent_function = base_type.class_type->get_member(p_context.current_function->identifier->name).function;
  1594. const GDScriptParser::ParameterNode *parameter = parent_function->parameters[parent_function->parameters_indices[p_identifier]];
  1595. if ((!id_type.is_set() || id_type.is_variant()) && parameter->get_datatype().is_hard_type()) {
  1596. id_type = parameter->get_datatype();
  1597. }
  1598. if (parameter->default_value) {
  1599. GDScriptParser::CompletionContext c = p_context;
  1600. c.current_function = parent_function;
  1601. c.current_class = base_type.class_type;
  1602. c.base = nullptr;
  1603. if (_guess_expression_type(c, parameter->default_value, r_type)) {
  1604. return true;
  1605. }
  1606. }
  1607. }
  1608. base_type = base_type.class_type->base_type;
  1609. break;
  1610. case GDScriptParser::DataType::NATIVE: {
  1611. if (id_type.is_set() && !id_type.is_variant()) {
  1612. base_type = GDScriptParser::DataType();
  1613. break;
  1614. }
  1615. MethodInfo info;
  1616. if (ClassDB::get_method_info(base_type.native_type, p_context.current_function->identifier->name, &info)) {
  1617. for (const PropertyInfo &E : info.arguments) {
  1618. if (E.name == p_identifier) {
  1619. r_type = _type_from_property(E);
  1620. return true;
  1621. }
  1622. }
  1623. }
  1624. base_type = GDScriptParser::DataType();
  1625. } break;
  1626. default:
  1627. break;
  1628. }
  1629. }
  1630. }
  1631. if (id_type.is_set() && !id_type.is_variant()) {
  1632. r_type.type = id_type;
  1633. return true;
  1634. }
  1635. // Check current class (including inheritance).
  1636. if (p_context.current_class) {
  1637. GDScriptCompletionIdentifier base;
  1638. base.value = p_context.base;
  1639. base.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1640. base.type.kind = GDScriptParser::DataType::CLASS;
  1641. base.type.class_type = p_context.current_class;
  1642. base.type.is_meta_type = p_context.current_function && p_context.current_function->is_static;
  1643. if (_guess_identifier_type_from_base(p_context, base, p_identifier, r_type)) {
  1644. return true;
  1645. }
  1646. }
  1647. // Check global scripts.
  1648. if (ScriptServer::is_global_class(p_identifier)) {
  1649. String script = ScriptServer::get_global_class_path(p_identifier);
  1650. if (script.to_lower().ends_with(".gd")) {
  1651. Error err = OK;
  1652. Ref<GDScriptParserRef> parser = GDScriptCache::get_parser(script, GDScriptParserRef::INTERFACE_SOLVED, err);
  1653. if (err == OK) {
  1654. r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1655. r_type.type.script_path = script;
  1656. r_type.type.class_type = parser->get_parser()->get_tree();
  1657. r_type.type.is_constant = false;
  1658. r_type.type.kind = GDScriptParser::DataType::CLASS;
  1659. r_type.value = Variant();
  1660. p_context.dependent_parsers.push_back(parser);
  1661. return true;
  1662. }
  1663. } else {
  1664. Ref<Script> scr = ResourceLoader::load(ScriptServer::get_global_class_path(p_identifier));
  1665. if (scr.is_valid()) {
  1666. r_type = _type_from_variant(scr);
  1667. r_type.type.is_meta_type = true;
  1668. return true;
  1669. }
  1670. }
  1671. return false;
  1672. }
  1673. // Check autoloads.
  1674. if (ProjectSettings::get_singleton()->has_autoload(p_identifier)) {
  1675. r_type = _type_from_variant(GDScriptLanguage::get_singleton()->get_named_globals_map()[p_identifier]);
  1676. return true;
  1677. }
  1678. // Check ClassDB.
  1679. if (ClassDB::class_exists(p_identifier) && ClassDB::is_class_exposed(p_identifier)) {
  1680. r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1681. r_type.type.kind = GDScriptParser::DataType::NATIVE;
  1682. r_type.type.native_type = p_identifier;
  1683. r_type.type.is_constant = true;
  1684. r_type.type.is_meta_type = !Engine::get_singleton()->has_singleton(p_identifier);
  1685. r_type.value = Variant();
  1686. }
  1687. return false;
  1688. }
  1689. static bool _guess_identifier_type_from_base(GDScriptParser::CompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_identifier, GDScriptCompletionIdentifier &r_type) {
  1690. GDScriptParser::DataType base_type = p_base.type;
  1691. bool is_static = base_type.is_meta_type;
  1692. while (base_type.is_set()) {
  1693. switch (base_type.kind) {
  1694. case GDScriptParser::DataType::CLASS:
  1695. if (base_type.class_type->has_member(p_identifier)) {
  1696. const GDScriptParser::ClassNode::Member &member = base_type.class_type->get_member(p_identifier);
  1697. switch (member.type) {
  1698. case GDScriptParser::ClassNode::Member::CONSTANT:
  1699. r_type.type = member.constant->get_datatype();
  1700. if (member.constant->initializer && member.constant->initializer->is_constant) {
  1701. r_type.value = member.constant->initializer->reduced_value;
  1702. }
  1703. return true;
  1704. case GDScriptParser::ClassNode::Member::VARIABLE:
  1705. if (!is_static) {
  1706. if (member.variable->initializer) {
  1707. const GDScriptParser::ExpressionNode *init = member.variable->initializer;
  1708. if (init->is_constant) {
  1709. r_type.value = init->reduced_value;
  1710. r_type = _type_from_variant(init->reduced_value);
  1711. return true;
  1712. } else if (init->start_line == p_context.current_line) {
  1713. return false;
  1714. // Detects if variable is assigned to itself
  1715. } else if (_is_expression_named_identifier(init, member.variable->identifier->name)) {
  1716. if (member.variable->initializer->get_datatype().is_set()) {
  1717. r_type.type = member.variable->initializer->get_datatype();
  1718. } else if (member.variable->get_datatype().is_set() && !member.variable->get_datatype().is_variant()) {
  1719. r_type.type = member.variable->get_datatype();
  1720. }
  1721. return true;
  1722. } else if (_guess_expression_type(p_context, init, r_type)) {
  1723. return true;
  1724. } else if (init->get_datatype().is_set() && !init->get_datatype().is_variant()) {
  1725. r_type.type = init->get_datatype();
  1726. return true;
  1727. }
  1728. } else if (member.variable->get_datatype().is_set() && !member.variable->get_datatype().is_variant()) {
  1729. r_type.type = member.variable->get_datatype();
  1730. return true;
  1731. }
  1732. }
  1733. // TODO: Check assignments in constructor.
  1734. return false;
  1735. case GDScriptParser::ClassNode::Member::ENUM:
  1736. r_type.type = member.m_enum->get_datatype();
  1737. r_type.enumeration = member.m_enum->identifier->name;
  1738. return true;
  1739. case GDScriptParser::ClassNode::Member::ENUM_VALUE:
  1740. r_type = _type_from_variant(member.enum_value.value);
  1741. return true;
  1742. case GDScriptParser::ClassNode::Member::SIGNAL:
  1743. r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1744. r_type.type.kind = GDScriptParser::DataType::BUILTIN;
  1745. r_type.type.builtin_type = Variant::SIGNAL;
  1746. return true;
  1747. case GDScriptParser::ClassNode::Member::FUNCTION:
  1748. if (is_static && !member.function->is_static) {
  1749. return false;
  1750. }
  1751. r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1752. r_type.type.kind = GDScriptParser::DataType::BUILTIN;
  1753. r_type.type.builtin_type = Variant::CALLABLE;
  1754. return true;
  1755. case GDScriptParser::ClassNode::Member::CLASS:
  1756. r_type.type.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT;
  1757. r_type.type.kind = GDScriptParser::DataType::CLASS;
  1758. r_type.type.class_type = member.m_class;
  1759. return true;
  1760. case GDScriptParser::ClassNode::Member::UNDEFINED:
  1761. return false; // Unreachable.
  1762. }
  1763. return false;
  1764. }
  1765. base_type = base_type.class_type->base_type;
  1766. break;
  1767. case GDScriptParser::DataType::SCRIPT: {
  1768. Ref<Script> scr = base_type.script_type;
  1769. if (scr.is_valid()) {
  1770. Map<StringName, Variant> constants;
  1771. scr->get_constants(&constants);
  1772. if (constants.has(p_identifier)) {
  1773. r_type = _type_from_variant(constants[p_identifier]);
  1774. return true;
  1775. }
  1776. if (!is_static) {
  1777. List<PropertyInfo> members;
  1778. scr->get_script_property_list(&members);
  1779. for (const PropertyInfo &prop : members) {
  1780. if (prop.name == p_identifier) {
  1781. r_type = _type_from_property(prop);
  1782. return true;
  1783. }
  1784. }
  1785. }
  1786. Ref<Script> parent = scr->get_base_script();
  1787. if (parent.is_valid()) {
  1788. base_type.script_type = parent;
  1789. } else {
  1790. base_type.kind = GDScriptParser::DataType::NATIVE;
  1791. base_type.native_type = scr->get_instance_base_type();
  1792. }
  1793. } else {
  1794. return false;
  1795. }
  1796. } break;
  1797. case GDScriptParser::DataType::NATIVE: {
  1798. StringName class_name = base_type.native_type;
  1799. if (!ClassDB::class_exists(class_name)) {
  1800. return false;
  1801. }
  1802. // Skip constants since they're all integers. Type does not matter because int has no members.
  1803. PropertyInfo prop;
  1804. if (ClassDB::get_property_info(class_name, p_identifier, &prop)) {
  1805. StringName getter = ClassDB::get_property_getter(class_name, p_identifier);
  1806. if (getter != StringName()) {
  1807. MethodBind *g = ClassDB::get_method(class_name, getter);
  1808. if (g) {
  1809. r_type = _type_from_property(g->get_return_info());
  1810. return true;
  1811. }
  1812. } else {
  1813. r_type = _type_from_property(prop);
  1814. return true;
  1815. }
  1816. }
  1817. return false;
  1818. } break;
  1819. case GDScriptParser::DataType::BUILTIN: {
  1820. Callable::CallError err;
  1821. Variant tmp;
  1822. Variant::construct(base_type.builtin_type, tmp, nullptr, 0, err);
  1823. if (err.error != Callable::CallError::CALL_OK) {
  1824. return false;
  1825. }
  1826. bool valid = false;
  1827. Variant res = tmp.get(p_identifier, &valid);
  1828. if (valid) {
  1829. r_type = _type_from_variant(res);
  1830. r_type.value = Variant();
  1831. r_type.type.is_constant = false;
  1832. return true;
  1833. }
  1834. return false;
  1835. } break;
  1836. default: {
  1837. return false;
  1838. } break;
  1839. }
  1840. }
  1841. return false;
  1842. }
  1843. static void _find_last_return_in_block(GDScriptParser::CompletionContext &p_context, int &r_last_return_line, const GDScriptParser::ExpressionNode **r_last_returned_value) {
  1844. if (!p_context.current_suite) {
  1845. return;
  1846. }
  1847. for (int i = 0; i < p_context.current_suite->statements.size(); i++) {
  1848. if (p_context.current_suite->statements[i]->start_line < r_last_return_line) {
  1849. break;
  1850. }
  1851. GDScriptParser::CompletionContext c = p_context;
  1852. switch (p_context.current_suite->statements[i]->type) {
  1853. case GDScriptParser::Node::FOR:
  1854. c.current_suite = static_cast<const GDScriptParser::ForNode *>(p_context.current_suite->statements[i])->loop;
  1855. _find_last_return_in_block(c, r_last_return_line, r_last_returned_value);
  1856. break;
  1857. case GDScriptParser::Node::WHILE:
  1858. c.current_suite = static_cast<const GDScriptParser::WhileNode *>(p_context.current_suite->statements[i])->loop;
  1859. _find_last_return_in_block(c, r_last_return_line, r_last_returned_value);
  1860. break;
  1861. case GDScriptParser::Node::IF: {
  1862. const GDScriptParser::IfNode *_if = static_cast<const GDScriptParser::IfNode *>(p_context.current_suite->statements[i]);
  1863. c.current_suite = _if->true_block;
  1864. _find_last_return_in_block(c, r_last_return_line, r_last_returned_value);
  1865. if (_if->false_block) {
  1866. c.current_suite = _if->false_block;
  1867. _find_last_return_in_block(c, r_last_return_line, r_last_returned_value);
  1868. }
  1869. } break;
  1870. case GDScriptParser::Node::MATCH: {
  1871. const GDScriptParser::MatchNode *match = static_cast<const GDScriptParser::MatchNode *>(p_context.current_suite->statements[i]);
  1872. for (int j = 0; j < match->branches.size(); j++) {
  1873. c.current_suite = match->branches[j]->block;
  1874. _find_last_return_in_block(c, r_last_return_line, r_last_returned_value);
  1875. }
  1876. } break;
  1877. case GDScriptParser::Node::RETURN: {
  1878. const GDScriptParser::ReturnNode *ret = static_cast<const GDScriptParser::ReturnNode *>(p_context.current_suite->statements[i]);
  1879. if (ret->return_value) {
  1880. if (ret->start_line > r_last_return_line) {
  1881. r_last_return_line = ret->start_line;
  1882. *r_last_returned_value = ret->return_value;
  1883. }
  1884. }
  1885. } break;
  1886. default:
  1887. break;
  1888. }
  1889. }
  1890. }
  1891. static bool _guess_method_return_type_from_base(GDScriptParser::CompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, GDScriptCompletionIdentifier &r_type) {
  1892. GDScriptParser::DataType base_type = p_base.type;
  1893. bool is_static = base_type.is_meta_type;
  1894. if (is_static && p_method == SNAME("new")) {
  1895. r_type.type = base_type;
  1896. r_type.type.is_meta_type = false;
  1897. r_type.type.is_constant = false;
  1898. return true;
  1899. }
  1900. while (base_type.is_set() && !base_type.is_variant()) {
  1901. switch (base_type.kind) {
  1902. case GDScriptParser::DataType::CLASS:
  1903. if (base_type.class_type->has_function(p_method)) {
  1904. const GDScriptParser::FunctionNode *method = base_type.class_type->get_member(p_method).function;
  1905. if (!is_static || method->is_static) {
  1906. int last_return_line = -1;
  1907. const GDScriptParser::ExpressionNode *last_returned_value = nullptr;
  1908. GDScriptParser::CompletionContext c = p_context;
  1909. c.current_class = base_type.class_type;
  1910. c.current_function = const_cast<GDScriptParser::FunctionNode *>(method);
  1911. c.current_suite = method->body;
  1912. _find_last_return_in_block(c, last_return_line, &last_returned_value);
  1913. if (last_returned_value) {
  1914. c.current_line = c.current_suite->end_line;
  1915. if (_guess_expression_type(c, last_returned_value, r_type)) {
  1916. return true;
  1917. }
  1918. if (method->get_datatype().is_set() && !method->get_datatype().is_variant()) {
  1919. r_type.type = method->get_datatype();
  1920. return true;
  1921. }
  1922. }
  1923. }
  1924. }
  1925. base_type = base_type.class_type->base_type;
  1926. break;
  1927. case GDScriptParser::DataType::SCRIPT: {
  1928. Ref<Script> scr = base_type.script_type;
  1929. if (scr.is_valid()) {
  1930. List<MethodInfo> methods;
  1931. scr->get_script_method_list(&methods);
  1932. for (const MethodInfo &mi : methods) {
  1933. if (mi.name == p_method) {
  1934. r_type = _type_from_property(mi.return_val);
  1935. return true;
  1936. }
  1937. }
  1938. Ref<Script> base_script = scr->get_base_script();
  1939. if (base_script.is_valid()) {
  1940. base_type.script_type = base_script;
  1941. } else {
  1942. base_type.kind = GDScriptParser::DataType::NATIVE;
  1943. base_type.native_type = scr->get_instance_base_type();
  1944. }
  1945. } else {
  1946. return false;
  1947. }
  1948. } break;
  1949. case GDScriptParser::DataType::NATIVE: {
  1950. if (!ClassDB::class_exists(base_type.native_type)) {
  1951. return false;
  1952. }
  1953. MethodBind *mb = ClassDB::get_method(base_type.native_type, p_method);
  1954. if (mb) {
  1955. r_type = _type_from_property(mb->get_return_info());
  1956. return true;
  1957. }
  1958. return false;
  1959. } break;
  1960. case GDScriptParser::DataType::BUILTIN: {
  1961. Callable::CallError err;
  1962. Variant tmp;
  1963. Variant::construct(base_type.builtin_type, tmp, nullptr, 0, err);
  1964. if (err.error != Callable::CallError::CALL_OK) {
  1965. return false;
  1966. }
  1967. List<MethodInfo> methods;
  1968. tmp.get_method_list(&methods);
  1969. for (const MethodInfo &mi : methods) {
  1970. if (mi.name == p_method) {
  1971. r_type = _type_from_property(mi.return_val);
  1972. return true;
  1973. }
  1974. }
  1975. return false;
  1976. } break;
  1977. default: {
  1978. return false;
  1979. }
  1980. }
  1981. }
  1982. return false;
  1983. }
  1984. static void _find_enumeration_candidates(GDScriptParser::CompletionContext &p_context, const String &p_enum_hint, Map<String, ScriptCodeCompletionOption> &r_result) {
  1985. if (!p_enum_hint.contains(".")) {
  1986. // Global constant or in the current class.
  1987. StringName current_enum = p_enum_hint;
  1988. if (p_context.current_class && p_context.current_class->has_member(current_enum) && p_context.current_class->get_member(current_enum).type == GDScriptParser::ClassNode::Member::ENUM) {
  1989. const GDScriptParser::EnumNode *_enum = p_context.current_class->get_member(current_enum).m_enum;
  1990. for (int i = 0; i < _enum->values.size(); i++) {
  1991. ScriptCodeCompletionOption option(_enum->values[i].identifier->name, ScriptCodeCompletionOption::KIND_ENUM);
  1992. r_result.insert(option.display, option);
  1993. }
  1994. } else {
  1995. for (int i = 0; i < CoreConstants::get_global_constant_count(); i++) {
  1996. if (CoreConstants::get_global_constant_enum(i) == current_enum) {
  1997. ScriptCodeCompletionOption option(CoreConstants::get_global_constant_name(i), ScriptCodeCompletionOption::KIND_ENUM);
  1998. r_result.insert(option.display, option);
  1999. }
  2000. }
  2001. }
  2002. } else {
  2003. String class_name = p_enum_hint.get_slice(".", 0);
  2004. String enum_name = p_enum_hint.get_slice(".", 1);
  2005. if (!ClassDB::class_exists(class_name)) {
  2006. return;
  2007. }
  2008. List<StringName> enum_constants;
  2009. ClassDB::get_enum_constants(class_name, enum_name, &enum_constants);
  2010. for (const StringName &E : enum_constants) {
  2011. String candidate = class_name + "." + E;
  2012. ScriptCodeCompletionOption option(candidate, ScriptCodeCompletionOption::KIND_ENUM);
  2013. r_result.insert(option.display, option);
  2014. }
  2015. }
  2016. }
  2017. static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, const GDScriptCompletionIdentifier &p_base, const StringName &p_method, int p_argidx, bool p_static, Map<String, ScriptCodeCompletionOption> &r_result, String &r_arghint) {
  2018. Variant base = p_base.value;
  2019. GDScriptParser::DataType base_type = p_base.type;
  2020. const String quote_style = EDITOR_GET("text_editor/completion/use_single_quotes") ? "'" : "\"";
  2021. while (base_type.is_set() && !base_type.is_variant()) {
  2022. switch (base_type.kind) {
  2023. case GDScriptParser::DataType::CLASS: {
  2024. if (base_type.class_type->has_member(p_method)) {
  2025. const GDScriptParser::ClassNode::Member &member = base_type.class_type->get_member(p_method);
  2026. if (member.type == GDScriptParser::ClassNode::Member::FUNCTION) {
  2027. r_arghint = _make_arguments_hint(member.function, p_argidx);
  2028. return;
  2029. }
  2030. }
  2031. base_type = base_type.class_type->base_type;
  2032. } break;
  2033. case GDScriptParser::DataType::NATIVE: {
  2034. StringName class_name = base_type.native_type;
  2035. if (!ClassDB::class_exists(class_name)) {
  2036. base_type.kind = GDScriptParser::DataType::UNRESOLVED;
  2037. break;
  2038. }
  2039. MethodInfo info;
  2040. int method_args = 0;
  2041. if (ClassDB::get_method_info(class_name, p_method, &info)) {
  2042. method_args = info.arguments.size();
  2043. if (base.get_type() == Variant::OBJECT) {
  2044. Object *obj = base.operator Object *();
  2045. if (obj) {
  2046. List<String> options;
  2047. obj->get_argument_options(p_method, p_argidx, &options);
  2048. for (String &opt : options) {
  2049. if (opt.is_quoted()) {
  2050. opt = opt.unquote().quote(quote_style); // Handle user preference.
  2051. }
  2052. ScriptCodeCompletionOption option(opt, ScriptCodeCompletionOption::KIND_FUNCTION);
  2053. r_result.insert(option.display, option);
  2054. }
  2055. }
  2056. }
  2057. if (p_argidx < method_args) {
  2058. PropertyInfo arg_info = info.arguments[p_argidx];
  2059. if (arg_info.usage & PROPERTY_USAGE_CLASS_IS_ENUM) {
  2060. _find_enumeration_candidates(p_context, arg_info.class_name, r_result);
  2061. }
  2062. }
  2063. r_arghint = _make_arguments_hint(info, p_argidx);
  2064. }
  2065. if (p_argidx == 0 && ClassDB::is_parent_class(class_name, SNAME("Node")) && (p_method == SNAME("get_node") || p_method == SNAME("has_node"))) {
  2066. // Get autoloads
  2067. List<PropertyInfo> props;
  2068. ProjectSettings::get_singleton()->get_property_list(&props);
  2069. for (const PropertyInfo &E : props) {
  2070. String s = E.name;
  2071. if (!s.begins_with("autoload/")) {
  2072. continue;
  2073. }
  2074. String name = s.get_slice("/", 1);
  2075. ScriptCodeCompletionOption option("/root/" + name, ScriptCodeCompletionOption::KIND_NODE_PATH);
  2076. option.insert_text = option.display.quote(quote_style);
  2077. r_result.insert(option.display, option);
  2078. }
  2079. }
  2080. if (p_argidx == 0 && method_args > 0 && ClassDB::is_parent_class(class_name, SNAME("InputEvent")) && p_method.operator String().contains("action")) {
  2081. // Get input actions
  2082. List<PropertyInfo> props;
  2083. ProjectSettings::get_singleton()->get_property_list(&props);
  2084. for (const PropertyInfo &E : props) {
  2085. String s = E.name;
  2086. if (!s.begins_with("input/")) {
  2087. continue;
  2088. }
  2089. String name = s.get_slice("/", 1);
  2090. ScriptCodeCompletionOption option(name, ScriptCodeCompletionOption::KIND_CONSTANT);
  2091. option.insert_text = option.display.quote(quote_style);
  2092. r_result.insert(option.display, option);
  2093. }
  2094. }
  2095. base_type.kind = GDScriptParser::DataType::UNRESOLVED;
  2096. } break;
  2097. case GDScriptParser::DataType::BUILTIN: {
  2098. if (base.get_type() == Variant::NIL) {
  2099. Callable::CallError err;
  2100. Variant::construct(base_type.builtin_type, base, nullptr, 0, err);
  2101. if (err.error != Callable::CallError::CALL_OK) {
  2102. return;
  2103. }
  2104. }
  2105. List<MethodInfo> methods;
  2106. base.get_method_list(&methods);
  2107. for (const MethodInfo &E : methods) {
  2108. if (E.name == p_method) {
  2109. r_arghint = _make_arguments_hint(E, p_argidx);
  2110. return;
  2111. }
  2112. }
  2113. base_type.kind = GDScriptParser::DataType::UNRESOLVED;
  2114. } break;
  2115. default: {
  2116. base_type.kind = GDScriptParser::DataType::UNRESOLVED;
  2117. } break;
  2118. }
  2119. }
  2120. }
  2121. static void _find_call_arguments(GDScriptParser::CompletionContext &p_context, const GDScriptParser::Node *p_call, int p_argidx, Map<String, ScriptCodeCompletionOption> &r_result, bool &r_forced, String &r_arghint) {
  2122. if (p_call->type == GDScriptParser::Node::PRELOAD) {
  2123. if (p_argidx == 0 && bool(EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths"))) {
  2124. _get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), r_result);
  2125. }
  2126. MethodInfo mi(PropertyInfo(Variant::OBJECT, "resource", PROPERTY_HINT_RESOURCE_TYPE, "Resource"), "preload", PropertyInfo(Variant::STRING, "path"));
  2127. r_arghint = _make_arguments_hint(mi, p_argidx);
  2128. return;
  2129. } else if (p_call->type != GDScriptParser::Node::CALL) {
  2130. return;
  2131. }
  2132. Variant base;
  2133. GDScriptParser::DataType base_type;
  2134. bool _static = false;
  2135. const GDScriptParser::CallNode *call = static_cast<const GDScriptParser::CallNode *>(p_call);
  2136. GDScriptParser::Node::Type callee_type = call->get_callee_type();
  2137. GDScriptCompletionIdentifier connect_base;
  2138. if (Variant::has_utility_function(call->function_name)) {
  2139. MethodInfo info = Variant::get_utility_function_info(call->function_name);
  2140. r_arghint = _make_arguments_hint(info, p_argidx);
  2141. return;
  2142. } else if (GDScriptUtilityFunctions::function_exists(call->function_name)) {
  2143. MethodInfo info = GDScriptUtilityFunctions::get_function_info(call->function_name);
  2144. r_arghint = _make_arguments_hint(info, p_argidx);
  2145. return;
  2146. } else if (GDScriptParser::get_builtin_type(call->function_name) < Variant::VARIANT_MAX) {
  2147. // Complete constructor
  2148. List<MethodInfo> constructors;
  2149. Variant::get_constructor_list(GDScriptParser::get_builtin_type(call->function_name), &constructors);
  2150. int i = 0;
  2151. for (const MethodInfo &E : constructors) {
  2152. if (p_argidx >= E.arguments.size()) {
  2153. continue;
  2154. }
  2155. if (i > 0) {
  2156. r_arghint += "\n";
  2157. }
  2158. r_arghint += _make_arguments_hint(E, p_argidx);
  2159. i++;
  2160. }
  2161. return;
  2162. } else if (call->is_super || callee_type == GDScriptParser::Node::IDENTIFIER) {
  2163. base = p_context.base;
  2164. if (p_context.current_class) {
  2165. base_type = p_context.current_class->get_datatype();
  2166. _static = !p_context.current_function || p_context.current_function->is_static;
  2167. }
  2168. } else if (callee_type == GDScriptParser::Node::SUBSCRIPT) {
  2169. const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(call->callee);
  2170. if (subscript->is_attribute) {
  2171. GDScriptCompletionIdentifier ci;
  2172. if (_guess_expression_type(p_context, subscript->base, ci)) {
  2173. base_type = ci.type;
  2174. base = ci.value;
  2175. } else {
  2176. return;
  2177. }
  2178. _static = base_type.is_meta_type;
  2179. }
  2180. } else {
  2181. return;
  2182. }
  2183. GDScriptCompletionIdentifier ci;
  2184. ci.type = base_type;
  2185. ci.value = base;
  2186. _find_call_arguments(p_context, ci, call->function_name, p_argidx, _static, r_result, r_arghint);
  2187. r_forced = r_result.size() > 0;
  2188. }
  2189. ::Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_forced, String &r_call_hint) {
  2190. const String quote_style = EDITOR_GET("text_editor/completion/use_single_quotes") ? "'" : "\"";
  2191. GDScriptParser parser;
  2192. GDScriptAnalyzer analyzer(&parser);
  2193. parser.parse(p_code, p_path, true);
  2194. analyzer.analyze();
  2195. r_forced = false;
  2196. Map<String, ScriptCodeCompletionOption> options;
  2197. GDScriptParser::CompletionContext completion_context = parser.get_completion_context();
  2198. completion_context.base = p_owner;
  2199. bool is_function = false;
  2200. switch (completion_context.type) {
  2201. case GDScriptParser::COMPLETION_NONE:
  2202. break;
  2203. case GDScriptParser::COMPLETION_ANNOTATION: {
  2204. List<MethodInfo> annotations;
  2205. parser.get_annotation_list(&annotations);
  2206. for (const MethodInfo &E : annotations) {
  2207. ScriptCodeCompletionOption option(E.name.substr(1), ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
  2208. if (E.arguments.size() > 0) {
  2209. option.insert_text += "(";
  2210. }
  2211. options.insert(option.display, option);
  2212. }
  2213. r_forced = true;
  2214. } break;
  2215. case GDScriptParser::COMPLETION_ANNOTATION_ARGUMENTS: {
  2216. if (completion_context.node == nullptr || completion_context.node->type != GDScriptParser::Node::ANNOTATION) {
  2217. break;
  2218. }
  2219. const GDScriptParser::AnnotationNode *annotation = static_cast<const GDScriptParser::AnnotationNode *>(completion_context.node);
  2220. _find_annotation_arguments(annotation, completion_context.current_argument, quote_style, options);
  2221. r_forced = true;
  2222. } break;
  2223. case GDScriptParser::COMPLETION_BUILT_IN_TYPE_CONSTANT: {
  2224. List<StringName> constants;
  2225. Variant::get_constants_for_type(completion_context.builtin_type, &constants);
  2226. for (const StringName &E : constants) {
  2227. ScriptCodeCompletionOption option(E, ScriptCodeCompletionOption::KIND_CONSTANT);
  2228. bool valid = false;
  2229. Variant default_value = Variant::get_constant_value(completion_context.builtin_type, E, &valid);
  2230. if (valid) {
  2231. option.default_value = default_value;
  2232. }
  2233. options.insert(option.display, option);
  2234. }
  2235. } break;
  2236. case GDScriptParser::COMPLETION_INHERIT_TYPE: {
  2237. _list_available_types(true, completion_context, options);
  2238. r_forced = true;
  2239. } break;
  2240. case GDScriptParser::COMPLETION_TYPE_NAME_OR_VOID: {
  2241. ScriptCodeCompletionOption option("void", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
  2242. options.insert(option.display, option);
  2243. }
  2244. [[fallthrough]];
  2245. case GDScriptParser::COMPLETION_TYPE_NAME: {
  2246. _list_available_types(false, completion_context, options);
  2247. r_forced = true;
  2248. } break;
  2249. case GDScriptParser::COMPLETION_PROPERTY_DECLARATION_OR_TYPE: {
  2250. _list_available_types(false, completion_context, options);
  2251. ScriptCodeCompletionOption get("get", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
  2252. options.insert(get.display, get);
  2253. ScriptCodeCompletionOption set("set", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
  2254. options.insert(set.display, set);
  2255. r_forced = true;
  2256. } break;
  2257. case GDScriptParser::COMPLETION_PROPERTY_DECLARATION: {
  2258. ScriptCodeCompletionOption get("get", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
  2259. options.insert(get.display, get);
  2260. ScriptCodeCompletionOption set("set", ScriptCodeCompletionOption::KIND_PLAIN_TEXT);
  2261. options.insert(set.display, set);
  2262. r_forced = true;
  2263. } break;
  2264. case GDScriptParser::COMPLETION_PROPERTY_METHOD: {
  2265. if (!completion_context.current_class) {
  2266. break;
  2267. }
  2268. for (int i = 0; i < completion_context.current_class->members.size(); i++) {
  2269. const GDScriptParser::ClassNode::Member &member = completion_context.current_class->members[i];
  2270. if (member.type != GDScriptParser::ClassNode::Member::FUNCTION) {
  2271. continue;
  2272. }
  2273. if (member.function->is_static) {
  2274. continue;
  2275. }
  2276. ScriptCodeCompletionOption option(member.function->identifier->name, ScriptCodeCompletionOption::KIND_FUNCTION);
  2277. options.insert(option.display, option);
  2278. }
  2279. r_forced = true;
  2280. } break;
  2281. case GDScriptParser::COMPLETION_ASSIGN: {
  2282. GDScriptCompletionIdentifier type;
  2283. if (!completion_context.node || completion_context.node->type != GDScriptParser::Node::ASSIGNMENT) {
  2284. break;
  2285. }
  2286. if (!_guess_expression_type(completion_context, static_cast<const GDScriptParser::AssignmentNode *>(completion_context.node)->assignee, type)) {
  2287. _find_identifiers(completion_context, false, options, 0);
  2288. r_forced = true;
  2289. break;
  2290. }
  2291. if (!type.enumeration.is_empty()) {
  2292. _find_enumeration_candidates(completion_context, type.enumeration, options);
  2293. r_forced = options.size() > 0;
  2294. } else {
  2295. _find_identifiers(completion_context, false, options, 0);
  2296. r_forced = true;
  2297. }
  2298. } break;
  2299. case GDScriptParser::COMPLETION_METHOD:
  2300. is_function = true;
  2301. [[fallthrough]];
  2302. case GDScriptParser::COMPLETION_IDENTIFIER: {
  2303. _find_identifiers(completion_context, is_function, options, 0);
  2304. } break;
  2305. case GDScriptParser::COMPLETION_ATTRIBUTE_METHOD:
  2306. is_function = true;
  2307. [[fallthrough]];
  2308. case GDScriptParser::COMPLETION_ATTRIBUTE: {
  2309. r_forced = true;
  2310. const GDScriptParser::SubscriptNode *attr = static_cast<const GDScriptParser::SubscriptNode *>(completion_context.node);
  2311. if (attr->base) {
  2312. GDScriptCompletionIdentifier base;
  2313. if (!_guess_expression_type(completion_context, attr->base, base)) {
  2314. break;
  2315. }
  2316. _find_identifiers_in_base(base, is_function, options, 0);
  2317. }
  2318. } break;
  2319. case GDScriptParser::COMPLETION_SUBSCRIPT: {
  2320. const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(completion_context.node);
  2321. GDScriptCompletionIdentifier base;
  2322. if (!_guess_expression_type(completion_context, subscript->base, base)) {
  2323. break;
  2324. }
  2325. GDScriptParser::CompletionContext c = completion_context;
  2326. c.current_function = nullptr;
  2327. c.current_suite = nullptr;
  2328. c.base = base.value.get_type() == Variant::OBJECT ? base.value.operator Object *() : nullptr;
  2329. if (base.type.kind == GDScriptParser::DataType::CLASS) {
  2330. c.current_class = base.type.class_type;
  2331. } else {
  2332. c.current_class = nullptr;
  2333. }
  2334. _find_identifiers_in_base(base, false, options, 0);
  2335. } break;
  2336. case GDScriptParser::COMPLETION_TYPE_ATTRIBUTE: {
  2337. if (!completion_context.current_class) {
  2338. break;
  2339. }
  2340. const GDScriptParser::TypeNode *type = static_cast<const GDScriptParser::TypeNode *>(completion_context.node);
  2341. bool found = true;
  2342. GDScriptCompletionIdentifier base;
  2343. base.type.kind = GDScriptParser::DataType::CLASS;
  2344. base.type.type_source = GDScriptParser::DataType::INFERRED;
  2345. base.type.is_constant = true;
  2346. base.type.class_type = completion_context.current_class;
  2347. base.value = completion_context.base;
  2348. for (int i = 0; i < completion_context.current_argument; i++) {
  2349. GDScriptCompletionIdentifier ci;
  2350. if (!_guess_identifier_type_from_base(completion_context, base, type->type_chain[i]->name, ci)) {
  2351. found = false;
  2352. break;
  2353. }
  2354. base = ci;
  2355. }
  2356. // TODO: Improve this to only list types.
  2357. if (found) {
  2358. _find_identifiers_in_base(base, false, options, 0);
  2359. }
  2360. r_forced = true;
  2361. } break;
  2362. case GDScriptParser::COMPLETION_RESOURCE_PATH: {
  2363. if (EditorSettings::get_singleton()->get("text_editor/completion/complete_file_paths")) {
  2364. _get_directory_contents(EditorFileSystem::get_singleton()->get_filesystem(), options);
  2365. r_forced = true;
  2366. }
  2367. } break;
  2368. case GDScriptParser::COMPLETION_CALL_ARGUMENTS: {
  2369. if (!completion_context.node) {
  2370. break;
  2371. }
  2372. _find_call_arguments(completion_context, completion_context.node, completion_context.current_argument, options, r_forced, r_call_hint);
  2373. } break;
  2374. case GDScriptParser::COMPLETION_OVERRIDE_METHOD: {
  2375. GDScriptParser::DataType native_type = completion_context.current_class->base_type;
  2376. while (native_type.is_set() && native_type.kind != GDScriptParser::DataType::NATIVE) {
  2377. switch (native_type.kind) {
  2378. case GDScriptParser::DataType::CLASS: {
  2379. native_type = native_type.class_type->base_type;
  2380. } break;
  2381. default: {
  2382. native_type.kind = GDScriptParser::DataType::UNRESOLVED;
  2383. } break;
  2384. }
  2385. }
  2386. if (!native_type.is_set()) {
  2387. break;
  2388. }
  2389. StringName class_name = native_type.native_type;
  2390. if (!ClassDB::class_exists(class_name)) {
  2391. break;
  2392. }
  2393. bool use_type_hint = EditorSettings::get_singleton()->get_setting("text_editor/completion/add_type_hints").operator bool();
  2394. List<MethodInfo> virtual_methods;
  2395. ClassDB::get_virtual_methods(class_name, &virtual_methods);
  2396. for (const MethodInfo &mi : virtual_methods) {
  2397. String method_hint = mi.name;
  2398. if (method_hint.contains(":")) {
  2399. method_hint = method_hint.get_slice(":", 0);
  2400. }
  2401. method_hint += "(";
  2402. if (mi.arguments.size()) {
  2403. for (int i = 0; i < mi.arguments.size(); i++) {
  2404. if (i > 0) {
  2405. method_hint += ", ";
  2406. }
  2407. String arg = mi.arguments[i].name;
  2408. if (arg.contains(":")) {
  2409. arg = arg.substr(0, arg.find(":"));
  2410. }
  2411. method_hint += arg;
  2412. if (use_type_hint && mi.arguments[i].type != Variant::NIL) {
  2413. method_hint += ": ";
  2414. if (mi.arguments[i].type == Variant::OBJECT && mi.arguments[i].class_name != StringName()) {
  2415. method_hint += mi.arguments[i].class_name.operator String();
  2416. } else {
  2417. method_hint += Variant::get_type_name(mi.arguments[i].type);
  2418. }
  2419. }
  2420. }
  2421. }
  2422. method_hint += ")";
  2423. if (use_type_hint && (mi.return_val.type != Variant::NIL || !(mi.return_val.usage & PROPERTY_USAGE_NIL_IS_VARIANT))) {
  2424. method_hint += " -> ";
  2425. if (mi.return_val.type == Variant::NIL) {
  2426. method_hint += "void";
  2427. } else if (mi.return_val.type == Variant::OBJECT && mi.return_val.class_name != StringName()) {
  2428. method_hint += mi.return_val.class_name.operator String();
  2429. } else {
  2430. method_hint += Variant::get_type_name(mi.return_val.type);
  2431. }
  2432. }
  2433. method_hint += ":";
  2434. ScriptCodeCompletionOption option(method_hint, ScriptCodeCompletionOption::KIND_FUNCTION);
  2435. options.insert(option.display, option);
  2436. }
  2437. } break;
  2438. case GDScriptParser::COMPLETION_GET_NODE: {
  2439. // Handles the `$Node/Path` or `$"Some NodePath"` syntax specifically.
  2440. if (p_owner) {
  2441. List<String> opts;
  2442. p_owner->get_argument_options("get_node", 0, &opts);
  2443. for (const String &E : opts) {
  2444. r_forced = true;
  2445. String opt = E.strip_edges();
  2446. if (opt.is_quoted()) {
  2447. // Remove quotes so that we can handle user preferred quote style,
  2448. // or handle NodePaths which are valid identifiers and don't need quotes.
  2449. opt = opt.unquote();
  2450. }
  2451. // The path needs quotes if it's not a valid identifier (with an exception
  2452. // for "/" as path separator, which also doesn't require quotes).
  2453. if (!opt.replace("/", "_").is_valid_identifier()) {
  2454. opt = opt.quote(quote_style); // Handle user preference.
  2455. }
  2456. ScriptCodeCompletionOption option(opt, ScriptCodeCompletionOption::KIND_NODE_PATH);
  2457. options.insert(option.display, option);
  2458. }
  2459. // Get autoloads.
  2460. OrderedHashMap<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
  2461. for (OrderedHashMap<StringName, ProjectSettings::AutoloadInfo>::Element E = autoloads.front(); E; E = E.next()) {
  2462. String path = "/root/" + E.key();
  2463. ScriptCodeCompletionOption option(path.quote(quote_style), ScriptCodeCompletionOption::KIND_NODE_PATH);
  2464. options.insert(option.display, option);
  2465. }
  2466. }
  2467. } break;
  2468. case GDScriptParser::COMPLETION_SUPER_METHOD: {
  2469. if (!completion_context.current_class) {
  2470. break;
  2471. }
  2472. _find_identifiers_in_class(completion_context.current_class, true, false, true, options, 0);
  2473. } break;
  2474. }
  2475. for (const KeyValue<String, ScriptCodeCompletionOption> &E : options) {
  2476. r_options->push_back(E.value);
  2477. }
  2478. return OK;
  2479. }
  2480. #else
  2481. Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_forced, String &r_call_hint) {
  2482. return OK;
  2483. }
  2484. #endif
  2485. //////// END COMPLETION //////////
  2486. String GDScriptLanguage::_get_indentation() const {
  2487. #ifdef TOOLS_ENABLED
  2488. if (Engine::get_singleton()->is_editor_hint()) {
  2489. bool use_space_indentation = EDITOR_GET("text_editor/behavior/indent/type");
  2490. if (use_space_indentation) {
  2491. int indent_size = EDITOR_GET("text_editor/behavior/indent/size");
  2492. String space_indent = "";
  2493. for (int i = 0; i < indent_size; i++) {
  2494. space_indent += " ";
  2495. }
  2496. return space_indent;
  2497. }
  2498. }
  2499. #endif
  2500. return "\t";
  2501. }
  2502. void GDScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_to_line) const {
  2503. String indent = _get_indentation();
  2504. Vector<String> lines = p_code.split("\n");
  2505. List<int> indent_stack;
  2506. for (int i = 0; i < lines.size(); i++) {
  2507. String l = lines[i];
  2508. int tc = 0;
  2509. for (int j = 0; j < l.length(); j++) {
  2510. if (l[j] == ' ' || l[j] == '\t') {
  2511. tc++;
  2512. } else {
  2513. break;
  2514. }
  2515. }
  2516. String st = l.substr(tc, l.length()).strip_edges();
  2517. if (st.is_empty() || st.begins_with("#")) {
  2518. continue; //ignore!
  2519. }
  2520. int ilevel = 0;
  2521. if (indent_stack.size()) {
  2522. ilevel = indent_stack.back()->get();
  2523. }
  2524. if (tc > ilevel) {
  2525. indent_stack.push_back(tc);
  2526. } else if (tc < ilevel) {
  2527. while (indent_stack.size() && indent_stack.back()->get() > tc) {
  2528. indent_stack.pop_back();
  2529. }
  2530. if (indent_stack.size() && indent_stack.back()->get() != tc) {
  2531. indent_stack.push_back(tc); // this is not right but gets the job done
  2532. }
  2533. }
  2534. if (i >= p_from_line) {
  2535. l = "";
  2536. for (int j = 0; j < indent_stack.size(); j++) {
  2537. l += indent;
  2538. }
  2539. l += st;
  2540. } else if (i > p_to_line) {
  2541. break;
  2542. }
  2543. lines.write[i] = l;
  2544. }
  2545. p_code = "";
  2546. for (int i = 0; i < lines.size(); i++) {
  2547. if (i > 0) {
  2548. p_code += "\n";
  2549. }
  2550. p_code += lines[i];
  2551. }
  2552. }
  2553. #ifdef TOOLS_ENABLED
  2554. static Error _lookup_symbol_from_base(const GDScriptParser::DataType &p_base, const String &p_symbol, bool p_is_function, GDScriptLanguage::LookupResult &r_result) {
  2555. GDScriptParser::DataType base_type = p_base;
  2556. while (base_type.is_set()) {
  2557. switch (base_type.kind) {
  2558. case GDScriptParser::DataType::CLASS: {
  2559. if (base_type.class_type) {
  2560. if (base_type.class_type->has_member(p_symbol)) {
  2561. r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
  2562. r_result.location = base_type.class_type->get_member(p_symbol).get_line();
  2563. r_result.class_path = base_type.script_path;
  2564. r_result.script = GDScriptCache::get_shallow_script(r_result.class_path);
  2565. return OK;
  2566. }
  2567. base_type = base_type.class_type->base_type;
  2568. }
  2569. } break;
  2570. case GDScriptParser::DataType::SCRIPT: {
  2571. Ref<Script> scr = base_type.script_type;
  2572. if (scr.is_valid()) {
  2573. int line = scr->get_member_line(p_symbol);
  2574. if (line >= 0) {
  2575. r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
  2576. r_result.location = line;
  2577. r_result.script = scr;
  2578. return OK;
  2579. }
  2580. Ref<Script> base_script = scr->get_base_script();
  2581. if (base_script.is_valid()) {
  2582. base_type.script_type = base_script;
  2583. } else {
  2584. base_type.kind = GDScriptParser::DataType::NATIVE;
  2585. base_type.native_type = scr->get_instance_base_type();
  2586. }
  2587. } else {
  2588. base_type.kind = GDScriptParser::DataType::UNRESOLVED;
  2589. }
  2590. } break;
  2591. case GDScriptParser::DataType::NATIVE: {
  2592. StringName class_name = base_type.native_type;
  2593. if (!ClassDB::class_exists(class_name)) {
  2594. base_type.kind = GDScriptParser::DataType::UNRESOLVED;
  2595. break;
  2596. }
  2597. if (ClassDB::has_method(class_name, p_symbol, true)) {
  2598. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
  2599. r_result.class_name = base_type.native_type;
  2600. r_result.class_member = p_symbol;
  2601. return OK;
  2602. }
  2603. List<MethodInfo> virtual_methods;
  2604. ClassDB::get_virtual_methods(class_name, &virtual_methods, true);
  2605. for (const MethodInfo &E : virtual_methods) {
  2606. if (E.name == p_symbol) {
  2607. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
  2608. r_result.class_name = base_type.native_type;
  2609. r_result.class_member = p_symbol;
  2610. return OK;
  2611. }
  2612. }
  2613. StringName enum_name = ClassDB::get_integer_constant_enum(class_name, p_symbol, true);
  2614. if (enum_name != StringName()) {
  2615. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_ENUM;
  2616. r_result.class_name = base_type.native_type;
  2617. r_result.class_member = enum_name;
  2618. return OK;
  2619. }
  2620. List<String> constants;
  2621. ClassDB::get_integer_constant_list(class_name, &constants, true);
  2622. for (const String &E : constants) {
  2623. if (E == p_symbol) {
  2624. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
  2625. r_result.class_name = base_type.native_type;
  2626. r_result.class_member = p_symbol;
  2627. return OK;
  2628. }
  2629. }
  2630. if (ClassDB::has_property(class_name, p_symbol, true)) {
  2631. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY;
  2632. r_result.class_name = base_type.native_type;
  2633. r_result.class_member = p_symbol;
  2634. return OK;
  2635. }
  2636. StringName parent = ClassDB::get_parent_class(class_name);
  2637. if (parent != StringName()) {
  2638. base_type.native_type = parent;
  2639. } else {
  2640. base_type.kind = GDScriptParser::DataType::UNRESOLVED;
  2641. }
  2642. } break;
  2643. case GDScriptParser::DataType::BUILTIN: {
  2644. base_type.kind = GDScriptParser::DataType::UNRESOLVED;
  2645. if (Variant::has_constant(base_type.builtin_type, p_symbol)) {
  2646. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
  2647. r_result.class_name = Variant::get_type_name(base_type.builtin_type);
  2648. r_result.class_member = p_symbol;
  2649. return OK;
  2650. }
  2651. Variant v;
  2652. REF v_ref;
  2653. if (base_type.builtin_type == Variant::OBJECT) {
  2654. v_ref.instantiate();
  2655. v = v_ref;
  2656. } else {
  2657. Callable::CallError err;
  2658. Variant::construct(base_type.builtin_type, v, nullptr, 0, err);
  2659. if (err.error != Callable::CallError::CALL_OK) {
  2660. break;
  2661. }
  2662. }
  2663. if (v.has_method(p_symbol)) {
  2664. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
  2665. r_result.class_name = Variant::get_type_name(base_type.builtin_type);
  2666. r_result.class_member = p_symbol;
  2667. return OK;
  2668. }
  2669. bool valid = false;
  2670. v.get(p_symbol, &valid);
  2671. if (valid) {
  2672. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_PROPERTY;
  2673. r_result.class_name = Variant::get_type_name(base_type.builtin_type);
  2674. r_result.class_member = p_symbol;
  2675. return OK;
  2676. }
  2677. } break;
  2678. default: {
  2679. base_type.kind = GDScriptParser::DataType::UNRESOLVED;
  2680. } break;
  2681. }
  2682. }
  2683. return ERR_CANT_RESOLVE;
  2684. }
  2685. ::Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol, const String &p_path, Object *p_owner, LookupResult &r_result) {
  2686. // Before parsing, try the usual stuff
  2687. if (ClassDB::class_exists(p_symbol)) {
  2688. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS;
  2689. r_result.class_name = p_symbol;
  2690. return OK;
  2691. }
  2692. for (int i = 0; i < Variant::VARIANT_MAX; i++) {
  2693. Variant::Type t = Variant::Type(i);
  2694. if (Variant::get_type_name(t) == p_symbol) {
  2695. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS;
  2696. r_result.class_name = Variant::get_type_name(t);
  2697. return OK;
  2698. }
  2699. }
  2700. if (GDScriptUtilityFunctions::function_exists(p_symbol)) {
  2701. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_METHOD;
  2702. r_result.class_name = "@GDScript";
  2703. r_result.class_member = p_symbol;
  2704. return OK;
  2705. }
  2706. if ("PI" == p_symbol || "TAU" == p_symbol || "INF" == p_symbol || "NAN" == p_symbol) {
  2707. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
  2708. r_result.class_name = "@GDScript";
  2709. r_result.class_member = p_symbol;
  2710. return OK;
  2711. }
  2712. GDScriptParser parser;
  2713. parser.parse(p_code, p_path, true);
  2714. GDScriptAnalyzer analyzer(&parser);
  2715. analyzer.analyze();
  2716. GDScriptParser::CompletionContext context = parser.get_completion_context();
  2717. if (context.current_class && context.current_class->extends.size() > 0) {
  2718. bool success = false;
  2719. ClassDB::get_integer_constant(context.current_class->extends[0], p_symbol, &success);
  2720. if (success) {
  2721. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
  2722. r_result.class_name = context.current_class->extends[0];
  2723. r_result.class_member = p_symbol;
  2724. return OK;
  2725. }
  2726. }
  2727. bool is_function = false;
  2728. switch (context.type) {
  2729. case GDScriptParser::COMPLETION_BUILT_IN_TYPE_CONSTANT: {
  2730. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
  2731. r_result.class_name = Variant::get_type_name(context.builtin_type);
  2732. r_result.class_member = p_symbol;
  2733. return OK;
  2734. } break;
  2735. case GDScriptParser::COMPLETION_SUPER_METHOD:
  2736. case GDScriptParser::COMPLETION_METHOD: {
  2737. is_function = true;
  2738. [[fallthrough]];
  2739. }
  2740. case GDScriptParser::COMPLETION_CALL_ARGUMENTS:
  2741. case GDScriptParser::COMPLETION_IDENTIFIER: {
  2742. GDScriptParser::DataType base_type;
  2743. if (context.current_class) {
  2744. if (context.type != GDScriptParser::COMPLETION_SUPER_METHOD) {
  2745. base_type = context.current_class->get_datatype();
  2746. } else {
  2747. base_type = context.current_class->base_type;
  2748. }
  2749. } else {
  2750. break;
  2751. }
  2752. if (!is_function && context.current_suite) {
  2753. // Lookup local variables.
  2754. const GDScriptParser::SuiteNode *suite = context.current_suite;
  2755. while (suite) {
  2756. if (suite->has_local(p_symbol)) {
  2757. r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
  2758. r_result.location = suite->get_local(p_symbol).start_line;
  2759. return OK;
  2760. }
  2761. suite = suite->parent_block;
  2762. }
  2763. }
  2764. if (_lookup_symbol_from_base(base_type, p_symbol, is_function, r_result) == OK) {
  2765. return OK;
  2766. }
  2767. if (!is_function) {
  2768. // Guess in autoloads as singletons.
  2769. if (ProjectSettings::get_singleton()->has_autoload(p_symbol)) {
  2770. const ProjectSettings::AutoloadInfo &autoload = ProjectSettings::get_singleton()->get_autoload(p_symbol);
  2771. if (autoload.is_singleton) {
  2772. String script = autoload.path;
  2773. if (!script.ends_with(".gd")) {
  2774. // Not a script, try find the script anyway,
  2775. // may have some success.
  2776. script = script.get_basename() + ".gd";
  2777. }
  2778. if (FileAccess::exists(script)) {
  2779. r_result.type = ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION;
  2780. r_result.location = 0;
  2781. r_result.script = ResourceLoader::load(script);
  2782. return OK;
  2783. }
  2784. }
  2785. }
  2786. // Global.
  2787. Map<StringName, int> classes = GDScriptLanguage::get_singleton()->get_global_map();
  2788. if (classes.has(p_symbol)) {
  2789. Variant value = GDScriptLanguage::get_singleton()->get_global_array()[classes[p_symbol]];
  2790. if (value.get_type() == Variant::OBJECT) {
  2791. Object *obj = value;
  2792. if (obj) {
  2793. if (Object::cast_to<GDScriptNativeClass>(obj)) {
  2794. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS;
  2795. r_result.class_name = Object::cast_to<GDScriptNativeClass>(obj)->get_name();
  2796. } else {
  2797. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS;
  2798. r_result.class_name = obj->get_class();
  2799. }
  2800. // proxy class remove the underscore.
  2801. if (r_result.class_name.begins_with("_")) {
  2802. r_result.class_name = r_result.class_name.substr(1);
  2803. }
  2804. return OK;
  2805. }
  2806. } else {
  2807. /*
  2808. // Because get_integer_constant_enum and get_integer_constant don't work on @GlobalScope
  2809. // We cannot determine the exact nature of the identifier here
  2810. // Otherwise these codes would work
  2811. StringName enumName = ClassDB::get_integer_constant_enum("@GlobalScope", p_symbol, true);
  2812. if (enumName != nullptr) {
  2813. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_ENUM;
  2814. r_result.class_name = "@GlobalScope";
  2815. r_result.class_member = enumName;
  2816. return OK;
  2817. }
  2818. else {
  2819. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_CONSTANT;
  2820. r_result.class_name = "@GlobalScope";
  2821. r_result.class_member = p_symbol;
  2822. return OK;
  2823. }*/
  2824. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_TBD_GLOBALSCOPE;
  2825. r_result.class_name = "@GlobalScope";
  2826. r_result.class_member = p_symbol;
  2827. return OK;
  2828. }
  2829. } else {
  2830. List<StringName> utility_functions;
  2831. Variant::get_utility_function_list(&utility_functions);
  2832. if (utility_functions.find(p_symbol) != nullptr) {
  2833. r_result.type = ScriptLanguage::LookupResult::RESULT_CLASS_TBD_GLOBALSCOPE;
  2834. r_result.class_name = "@GlobalScope";
  2835. r_result.class_member = p_symbol;
  2836. return OK;
  2837. }
  2838. }
  2839. }
  2840. } break;
  2841. case GDScriptParser::COMPLETION_ATTRIBUTE_METHOD: {
  2842. is_function = true;
  2843. [[fallthrough]];
  2844. }
  2845. case GDScriptParser::COMPLETION_ATTRIBUTE: {
  2846. if (context.node->type != GDScriptParser::Node::SUBSCRIPT) {
  2847. break;
  2848. }
  2849. const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(context.node);
  2850. if (!subscript->is_attribute) {
  2851. break;
  2852. }
  2853. GDScriptCompletionIdentifier base;
  2854. if (!_guess_expression_type(context, subscript->base, base)) {
  2855. break;
  2856. }
  2857. if (_lookup_symbol_from_base(base.type, p_symbol, is_function, r_result) == OK) {
  2858. return OK;
  2859. }
  2860. } break;
  2861. case GDScriptParser::COMPLETION_OVERRIDE_METHOD: {
  2862. GDScriptParser::DataType base_type = context.current_class->base_type;
  2863. if (_lookup_symbol_from_base(base_type, p_symbol, true, r_result) == OK) {
  2864. return OK;
  2865. }
  2866. } break;
  2867. case GDScriptParser::COMPLETION_TYPE_NAME_OR_VOID:
  2868. case GDScriptParser::COMPLETION_TYPE_NAME: {
  2869. GDScriptParser::DataType base_type = context.current_class->get_datatype();
  2870. if (_lookup_symbol_from_base(base_type, p_symbol, false, r_result) == OK) {
  2871. return OK;
  2872. }
  2873. } break;
  2874. default: {
  2875. }
  2876. }
  2877. return ERR_CANT_RESOLVE;
  2878. }
  2879. #endif