gdscript_editor.cpp 112 KB

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