gdscript_editor.cpp 111 KB

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