gdscript_workspace.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  1. /**************************************************************************/
  2. /* gdscript_workspace.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  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_workspace.h"
  31. #include "../gdscript.h"
  32. #include "../gdscript_parser.h"
  33. #include "gdscript_language_protocol.h"
  34. #include "core/config/project_settings.h"
  35. #include "core/object/script_language.h"
  36. #include "editor/doc_tools.h"
  37. #include "editor/editor_file_system.h"
  38. #include "editor/editor_help.h"
  39. #include "editor/editor_node.h"
  40. #include "editor/editor_settings.h"
  41. #include "scene/resources/packed_scene.h"
  42. void GDScriptWorkspace::_bind_methods() {
  43. ClassDB::bind_method(D_METHOD("apply_new_signal"), &GDScriptWorkspace::apply_new_signal);
  44. ClassDB::bind_method(D_METHOD("didDeleteFiles"), &GDScriptWorkspace::didDeleteFiles);
  45. ClassDB::bind_method(D_METHOD("parse_script", "path", "content"), &GDScriptWorkspace::parse_script);
  46. ClassDB::bind_method(D_METHOD("parse_local_script", "path"), &GDScriptWorkspace::parse_local_script);
  47. ClassDB::bind_method(D_METHOD("get_file_path", "uri"), &GDScriptWorkspace::get_file_path);
  48. ClassDB::bind_method(D_METHOD("get_file_uri", "path"), &GDScriptWorkspace::get_file_uri);
  49. ClassDB::bind_method(D_METHOD("publish_diagnostics", "path"), &GDScriptWorkspace::publish_diagnostics);
  50. ClassDB::bind_method(D_METHOD("generate_script_api", "path"), &GDScriptWorkspace::generate_script_api);
  51. }
  52. void GDScriptWorkspace::apply_new_signal(Object *obj, String function, PackedStringArray args) {
  53. Ref<Script> scr = obj->get_script();
  54. if (scr->get_language()->get_name() != "GDScript") {
  55. return;
  56. }
  57. String function_signature = "func " + function;
  58. String source = scr->get_source_code();
  59. if (source.contains(function_signature)) {
  60. return;
  61. }
  62. int first_class = source.find("\nclass ");
  63. int start_line = 0;
  64. if (first_class != -1) {
  65. start_line = source.substr(0, first_class).split("\n").size();
  66. } else {
  67. start_line = source.split("\n").size();
  68. }
  69. String function_body = "\n\n" + function_signature + "(";
  70. for (int i = 0; i < args.size(); ++i) {
  71. function_body += args[i];
  72. if (i < args.size() - 1) {
  73. function_body += ", ";
  74. }
  75. }
  76. function_body += ")";
  77. if (EditorSettings::get_singleton()->get_setting("text_editor/completion/add_type_hints")) {
  78. function_body += " -> void";
  79. }
  80. function_body += ":\n\tpass # Replace with function body.\n";
  81. LSP::TextEdit text_edit;
  82. if (first_class != -1) {
  83. function_body += "\n\n";
  84. }
  85. text_edit.range.end.line = text_edit.range.start.line = start_line;
  86. text_edit.newText = function_body;
  87. String uri = get_file_uri(scr->get_path());
  88. LSP::ApplyWorkspaceEditParams params;
  89. params.edit.add_edit(uri, text_edit);
  90. GDScriptLanguageProtocol::get_singleton()->request_client("workspace/applyEdit", params.to_json());
  91. }
  92. void GDScriptWorkspace::didDeleteFiles(const Dictionary &p_params) {
  93. Array files = p_params["files"];
  94. for (int i = 0; i < files.size(); ++i) {
  95. Dictionary file = files[i];
  96. String uri = file["uri"];
  97. String path = get_file_path(uri);
  98. parse_script(path, "");
  99. }
  100. }
  101. void GDScriptWorkspace::remove_cache_parser(const String &p_path) {
  102. HashMap<String, ExtendGDScriptParser *>::Iterator parser = parse_results.find(p_path);
  103. HashMap<String, ExtendGDScriptParser *>::Iterator scr = scripts.find(p_path);
  104. if (parser && scr) {
  105. if (scr->value && scr->value == parser->value) {
  106. memdelete(scr->value);
  107. } else {
  108. memdelete(scr->value);
  109. memdelete(parser->value);
  110. }
  111. parse_results.erase(p_path);
  112. scripts.erase(p_path);
  113. } else if (parser) {
  114. memdelete(parser->value);
  115. parse_results.erase(p_path);
  116. } else if (scr) {
  117. memdelete(scr->value);
  118. scripts.erase(p_path);
  119. }
  120. }
  121. const LSP::DocumentSymbol *GDScriptWorkspace::get_native_symbol(const String &p_class, const String &p_member) const {
  122. StringName class_name = p_class;
  123. StringName empty;
  124. while (class_name != empty) {
  125. if (HashMap<StringName, LSP::DocumentSymbol>::ConstIterator E = native_symbols.find(class_name)) {
  126. const LSP::DocumentSymbol &class_symbol = E->value;
  127. if (p_member.is_empty()) {
  128. return &class_symbol;
  129. } else {
  130. for (int i = 0; i < class_symbol.children.size(); i++) {
  131. const LSP::DocumentSymbol &symbol = class_symbol.children[i];
  132. if (symbol.name == p_member) {
  133. return &symbol;
  134. }
  135. }
  136. }
  137. }
  138. class_name = ClassDB::get_parent_class(class_name);
  139. }
  140. return nullptr;
  141. }
  142. const LSP::DocumentSymbol *GDScriptWorkspace::get_script_symbol(const String &p_path) const {
  143. HashMap<String, ExtendGDScriptParser *>::ConstIterator S = scripts.find(p_path);
  144. if (S) {
  145. return &(S->value->get_symbols());
  146. }
  147. return nullptr;
  148. }
  149. const LSP::DocumentSymbol *GDScriptWorkspace::get_parameter_symbol(const LSP::DocumentSymbol *p_parent, const String &symbol_identifier) {
  150. for (int i = 0; i < p_parent->children.size(); ++i) {
  151. const LSP::DocumentSymbol *parameter_symbol = &p_parent->children[i];
  152. if (!parameter_symbol->detail.is_empty() && parameter_symbol->name == symbol_identifier) {
  153. return parameter_symbol;
  154. }
  155. }
  156. return nullptr;
  157. }
  158. const LSP::DocumentSymbol *GDScriptWorkspace::get_local_symbol_at(const ExtendGDScriptParser *p_parser, const String &p_symbol_identifier, const LSP::Position p_position) {
  159. // Go down and pick closest `DocumentSymbol` with `p_symbol_identifier`.
  160. const LSP::DocumentSymbol *current = &p_parser->get_symbols();
  161. const LSP::DocumentSymbol *best_match = nullptr;
  162. while (current) {
  163. if (current->name == p_symbol_identifier) {
  164. if (current->selectionRange.contains(p_position)) {
  165. // Exact match: pos is ON symbol decl identifier.
  166. return current;
  167. }
  168. best_match = current;
  169. }
  170. const LSP::DocumentSymbol *parent = current;
  171. current = nullptr;
  172. for (const LSP::DocumentSymbol &child : parent->children) {
  173. if (child.range.contains(p_position)) {
  174. current = &child;
  175. break;
  176. }
  177. }
  178. }
  179. return best_match;
  180. }
  181. void GDScriptWorkspace::reload_all_workspace_scripts() {
  182. List<String> paths;
  183. list_script_files("res://", paths);
  184. for (const String &path : paths) {
  185. Error err;
  186. String content = FileAccess::get_file_as_string(path, &err);
  187. ERR_CONTINUE(err != OK);
  188. err = parse_script(path, content);
  189. if (err != OK) {
  190. HashMap<String, ExtendGDScriptParser *>::Iterator S = parse_results.find(path);
  191. String err_msg = "Failed parse script " + path;
  192. if (S) {
  193. err_msg += "\n" + S->value->get_errors().front()->get().message;
  194. }
  195. ERR_CONTINUE_MSG(err != OK, err_msg);
  196. }
  197. }
  198. }
  199. void GDScriptWorkspace::list_script_files(const String &p_root_dir, List<String> &r_files) {
  200. Error err;
  201. Ref<DirAccess> dir = DirAccess::open(p_root_dir, &err);
  202. if (OK != err) {
  203. return;
  204. }
  205. // Ignore scripts in directories with a .gdignore file.
  206. if (dir->file_exists(".gdignore")) {
  207. return;
  208. }
  209. dir->list_dir_begin();
  210. String file_name = dir->get_next();
  211. while (file_name.length()) {
  212. if (dir->current_is_dir() && file_name != "." && file_name != ".." && file_name != "./") {
  213. list_script_files(p_root_dir.path_join(file_name), r_files);
  214. } else if (file_name.ends_with(".gd")) {
  215. String script_file = p_root_dir.path_join(file_name);
  216. r_files.push_back(script_file);
  217. }
  218. file_name = dir->get_next();
  219. }
  220. }
  221. ExtendGDScriptParser *GDScriptWorkspace::get_parse_successed_script(const String &p_path) {
  222. HashMap<String, ExtendGDScriptParser *>::Iterator S = scripts.find(p_path);
  223. if (!S) {
  224. parse_local_script(p_path);
  225. S = scripts.find(p_path);
  226. }
  227. if (S) {
  228. return S->value;
  229. }
  230. return nullptr;
  231. }
  232. ExtendGDScriptParser *GDScriptWorkspace::get_parse_result(const String &p_path) {
  233. HashMap<String, ExtendGDScriptParser *>::Iterator S = parse_results.find(p_path);
  234. if (!S) {
  235. parse_local_script(p_path);
  236. S = parse_results.find(p_path);
  237. }
  238. if (S) {
  239. return S->value;
  240. }
  241. return nullptr;
  242. }
  243. #define HANDLE_DOC(m_string) ((is_native ? DTR(m_string) : (m_string)).strip_edges())
  244. Error GDScriptWorkspace::initialize() {
  245. if (initialized) {
  246. return OK;
  247. }
  248. DocTools *doc = EditorHelp::get_doc_data();
  249. for (const KeyValue<String, DocData::ClassDoc> &E : doc->class_list) {
  250. const DocData::ClassDoc &class_data = E.value;
  251. const bool is_native = !class_data.is_script_doc;
  252. LSP::DocumentSymbol class_symbol;
  253. String class_name = E.key;
  254. class_symbol.name = class_name;
  255. class_symbol.native_class = class_name;
  256. class_symbol.kind = LSP::SymbolKind::Class;
  257. class_symbol.detail = String("<Native> class ") + class_name;
  258. if (!class_data.inherits.is_empty()) {
  259. class_symbol.detail += " extends " + class_data.inherits;
  260. }
  261. class_symbol.documentation = HANDLE_DOC(class_data.brief_description) + "\n" + HANDLE_DOC(class_data.description);
  262. for (int i = 0; i < class_data.constants.size(); i++) {
  263. const DocData::ConstantDoc &const_data = class_data.constants[i];
  264. LSP::DocumentSymbol symbol;
  265. symbol.name = const_data.name;
  266. symbol.native_class = class_name;
  267. symbol.kind = LSP::SymbolKind::Constant;
  268. symbol.detail = "const " + class_name + "." + const_data.name;
  269. if (const_data.enumeration.length()) {
  270. symbol.detail += ": " + const_data.enumeration;
  271. }
  272. symbol.detail += " = " + const_data.value;
  273. symbol.documentation = HANDLE_DOC(const_data.description);
  274. class_symbol.children.push_back(symbol);
  275. }
  276. for (int i = 0; i < class_data.properties.size(); i++) {
  277. const DocData::PropertyDoc &data = class_data.properties[i];
  278. LSP::DocumentSymbol symbol;
  279. symbol.name = data.name;
  280. symbol.native_class = class_name;
  281. symbol.kind = LSP::SymbolKind::Property;
  282. symbol.detail = "var " + class_name + "." + data.name;
  283. if (data.enumeration.length()) {
  284. symbol.detail += ": " + data.enumeration;
  285. } else {
  286. symbol.detail += ": " + data.type;
  287. }
  288. symbol.documentation = HANDLE_DOC(data.description);
  289. class_symbol.children.push_back(symbol);
  290. }
  291. for (int i = 0; i < class_data.theme_properties.size(); i++) {
  292. const DocData::ThemeItemDoc &data = class_data.theme_properties[i];
  293. LSP::DocumentSymbol symbol;
  294. symbol.name = data.name;
  295. symbol.native_class = class_name;
  296. symbol.kind = LSP::SymbolKind::Property;
  297. symbol.detail = "<Theme> var " + class_name + "." + data.name + ": " + data.type;
  298. symbol.documentation = HANDLE_DOC(data.description);
  299. class_symbol.children.push_back(symbol);
  300. }
  301. Vector<DocData::MethodDoc> methods_signals;
  302. methods_signals.append_array(class_data.constructors);
  303. methods_signals.append_array(class_data.methods);
  304. methods_signals.append_array(class_data.operators);
  305. const int signal_start_idx = methods_signals.size();
  306. methods_signals.append_array(class_data.signals);
  307. for (int i = 0; i < methods_signals.size(); i++) {
  308. const DocData::MethodDoc &data = methods_signals[i];
  309. LSP::DocumentSymbol symbol;
  310. symbol.name = data.name;
  311. symbol.native_class = class_name;
  312. symbol.kind = i >= signal_start_idx ? LSP::SymbolKind::Event : LSP::SymbolKind::Method;
  313. String params = "";
  314. bool arg_default_value_started = false;
  315. for (int j = 0; j < data.arguments.size(); j++) {
  316. const DocData::ArgumentDoc &arg = data.arguments[j];
  317. LSP::DocumentSymbol symbol_arg;
  318. symbol_arg.name = arg.name;
  319. symbol_arg.kind = LSP::SymbolKind::Variable;
  320. symbol_arg.detail = arg.type;
  321. if (!arg_default_value_started && !arg.default_value.is_empty()) {
  322. arg_default_value_started = true;
  323. }
  324. String arg_str = arg.name + ": " + arg.type;
  325. if (arg_default_value_started) {
  326. arg_str += " = " + arg.default_value;
  327. }
  328. if (j < data.arguments.size() - 1) {
  329. arg_str += ", ";
  330. }
  331. params += arg_str;
  332. symbol.children.push_back(symbol_arg);
  333. }
  334. if (data.qualifiers.contains("vararg")) {
  335. params += params.is_empty() ? "..." : ", ...";
  336. }
  337. String return_type = data.return_type;
  338. if (return_type.is_empty()) {
  339. return_type = "void";
  340. }
  341. symbol.detail = "func " + class_name + "." + data.name + "(" + params + ") -> " + return_type;
  342. symbol.documentation = HANDLE_DOC(data.description);
  343. class_symbol.children.push_back(symbol);
  344. }
  345. native_symbols.insert(class_name, class_symbol);
  346. }
  347. reload_all_workspace_scripts();
  348. if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
  349. for (const KeyValue<StringName, LSP::DocumentSymbol> &E : native_symbols) {
  350. ClassMembers members;
  351. const LSP::DocumentSymbol &class_symbol = E.value;
  352. for (int i = 0; i < class_symbol.children.size(); i++) {
  353. const LSP::DocumentSymbol &symbol = class_symbol.children[i];
  354. members.insert(symbol.name, &symbol);
  355. }
  356. native_members.insert(E.key, members);
  357. }
  358. // Cache member completions.
  359. for (const KeyValue<String, ExtendGDScriptParser *> &S : scripts) {
  360. S.value->get_member_completions();
  361. }
  362. }
  363. EditorNode *editor_node = EditorNode::get_singleton();
  364. editor_node->connect("script_add_function_request", callable_mp(this, &GDScriptWorkspace::apply_new_signal));
  365. return OK;
  366. }
  367. Error GDScriptWorkspace::parse_script(const String &p_path, const String &p_content) {
  368. ExtendGDScriptParser *parser = memnew(ExtendGDScriptParser);
  369. Error err = parser->parse(p_content, p_path);
  370. HashMap<String, ExtendGDScriptParser *>::Iterator last_parser = parse_results.find(p_path);
  371. HashMap<String, ExtendGDScriptParser *>::Iterator last_script = scripts.find(p_path);
  372. if (err == OK) {
  373. remove_cache_parser(p_path);
  374. parse_results[p_path] = parser;
  375. scripts[p_path] = parser;
  376. } else {
  377. if (last_parser && last_script && last_parser->value != last_script->value) {
  378. memdelete(last_parser->value);
  379. }
  380. parse_results[p_path] = parser;
  381. }
  382. publish_diagnostics(p_path);
  383. return err;
  384. }
  385. static bool is_valid_rename_target(const LSP::DocumentSymbol *p_symbol) {
  386. // Must be valid symbol.
  387. if (!p_symbol) {
  388. return false;
  389. }
  390. // Cannot rename builtin.
  391. if (!p_symbol->native_class.is_empty()) {
  392. return false;
  393. }
  394. // Source must be available.
  395. if (p_symbol->script_path.is_empty()) {
  396. return false;
  397. }
  398. return true;
  399. }
  400. Dictionary GDScriptWorkspace::rename(const LSP::TextDocumentPositionParams &p_doc_pos, const String &new_name) {
  401. LSP::WorkspaceEdit edit;
  402. const LSP::DocumentSymbol *reference_symbol = resolve_symbol(p_doc_pos);
  403. if (is_valid_rename_target(reference_symbol)) {
  404. Vector<LSP::Location> usages = find_all_usages(*reference_symbol);
  405. for (int i = 0; i < usages.size(); ++i) {
  406. LSP::Location loc = usages[i];
  407. edit.add_change(loc.uri, loc.range.start.line, loc.range.start.character, loc.range.end.character, new_name);
  408. }
  409. }
  410. return edit.to_json();
  411. }
  412. bool GDScriptWorkspace::can_rename(const LSP::TextDocumentPositionParams &p_doc_pos, LSP::DocumentSymbol &r_symbol, LSP::Range &r_range) {
  413. const LSP::DocumentSymbol *reference_symbol = resolve_symbol(p_doc_pos);
  414. if (!is_valid_rename_target(reference_symbol)) {
  415. return false;
  416. }
  417. String path = get_file_path(p_doc_pos.textDocument.uri);
  418. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  419. // We only care about the range.
  420. _ALLOW_DISCARD_ parser->get_identifier_under_position(p_doc_pos.position, r_range);
  421. r_symbol = *reference_symbol;
  422. return true;
  423. }
  424. return false;
  425. }
  426. Vector<LSP::Location> GDScriptWorkspace::find_usages_in_file(const LSP::DocumentSymbol &p_symbol, const String &p_file_path) {
  427. Vector<LSP::Location> usages;
  428. String identifier = p_symbol.name;
  429. if (const ExtendGDScriptParser *parser = get_parse_result(p_file_path)) {
  430. const PackedStringArray &content = parser->get_lines();
  431. for (int i = 0; i < content.size(); ++i) {
  432. String line = content[i];
  433. int character = line.find(identifier);
  434. while (character > -1) {
  435. LSP::TextDocumentPositionParams params;
  436. LSP::TextDocumentIdentifier text_doc;
  437. text_doc.uri = get_file_uri(p_file_path);
  438. params.textDocument = text_doc;
  439. params.position.line = i;
  440. params.position.character = character;
  441. const LSP::DocumentSymbol *other_symbol = resolve_symbol(params);
  442. if (other_symbol == &p_symbol) {
  443. LSP::Location loc;
  444. loc.uri = text_doc.uri;
  445. loc.range.start = params.position;
  446. loc.range.end.line = params.position.line;
  447. loc.range.end.character = params.position.character + identifier.length();
  448. usages.append(loc);
  449. }
  450. character = line.find(identifier, character + 1);
  451. }
  452. }
  453. }
  454. return usages;
  455. }
  456. Vector<LSP::Location> GDScriptWorkspace::find_all_usages(const LSP::DocumentSymbol &p_symbol) {
  457. if (p_symbol.local) {
  458. // Only search in current document.
  459. return find_usages_in_file(p_symbol, p_symbol.script_path);
  460. }
  461. // Search in all documents.
  462. List<String> paths;
  463. list_script_files("res://", paths);
  464. Vector<LSP::Location> usages;
  465. for (const String &path : paths) {
  466. usages.append_array(find_usages_in_file(p_symbol, path));
  467. }
  468. return usages;
  469. }
  470. Error GDScriptWorkspace::parse_local_script(const String &p_path) {
  471. Error err;
  472. String content = FileAccess::get_file_as_string(p_path, &err);
  473. if (err == OK) {
  474. err = parse_script(p_path, content);
  475. }
  476. return err;
  477. }
  478. String GDScriptWorkspace::get_file_path(const String &p_uri) const {
  479. String path = p_uri.uri_file_decode();
  480. String base_uri = root_uri.uri_file_decode();
  481. path = path.replacen(base_uri + "/", "res://");
  482. return path;
  483. }
  484. String GDScriptWorkspace::get_file_uri(const String &p_path) const {
  485. String uri = p_path;
  486. uri = uri.replace("res://", root_uri + "/");
  487. return uri;
  488. }
  489. void GDScriptWorkspace::publish_diagnostics(const String &p_path) {
  490. Dictionary params;
  491. Array errors;
  492. HashMap<String, ExtendGDScriptParser *>::ConstIterator ele = parse_results.find(p_path);
  493. if (ele) {
  494. const Vector<LSP::Diagnostic> &list = ele->value->get_diagnostics();
  495. errors.resize(list.size());
  496. for (int i = 0; i < list.size(); ++i) {
  497. errors[i] = list[i].to_json();
  498. }
  499. }
  500. params["diagnostics"] = errors;
  501. params["uri"] = get_file_uri(p_path);
  502. GDScriptLanguageProtocol::get_singleton()->notify_client("textDocument/publishDiagnostics", params);
  503. }
  504. void GDScriptWorkspace::_get_owners(EditorFileSystemDirectory *efsd, String p_path, List<String> &owners) {
  505. if (!efsd) {
  506. return;
  507. }
  508. for (int i = 0; i < efsd->get_subdir_count(); i++) {
  509. _get_owners(efsd->get_subdir(i), p_path, owners);
  510. }
  511. for (int i = 0; i < efsd->get_file_count(); i++) {
  512. Vector<String> deps = efsd->get_file_deps(i);
  513. bool found = false;
  514. for (int j = 0; j < deps.size(); j++) {
  515. if (deps[j] == p_path) {
  516. found = true;
  517. break;
  518. }
  519. }
  520. if (!found) {
  521. continue;
  522. }
  523. owners.push_back(efsd->get_file_path(i));
  524. }
  525. }
  526. Node *GDScriptWorkspace::_get_owner_scene_node(String p_path) {
  527. Node *owner_scene_node = nullptr;
  528. List<String> owners;
  529. _get_owners(EditorFileSystem::get_singleton()->get_filesystem(), p_path, owners);
  530. for (const String &owner : owners) {
  531. NodePath owner_path = owner;
  532. Ref<Resource> owner_res = ResourceLoader::load(String(owner_path));
  533. if (Object::cast_to<PackedScene>(owner_res.ptr())) {
  534. Ref<PackedScene> owner_packed_scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*owner_res));
  535. owner_scene_node = owner_packed_scene->instantiate();
  536. break;
  537. }
  538. }
  539. return owner_scene_node;
  540. }
  541. void GDScriptWorkspace::completion(const LSP::CompletionParams &p_params, List<ScriptLanguage::CodeCompletionOption> *r_options) {
  542. String path = get_file_path(p_params.textDocument.uri);
  543. String call_hint;
  544. bool forced = false;
  545. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  546. Node *owner_scene_node = _get_owner_scene_node(path);
  547. Array stack;
  548. Node *current = nullptr;
  549. if (owner_scene_node != nullptr) {
  550. stack.push_back(owner_scene_node);
  551. while (!stack.is_empty()) {
  552. current = Object::cast_to<Node>(stack.pop_back());
  553. Ref<GDScript> scr = current->get_script();
  554. if (scr.is_valid() && GDScript::is_canonically_equal_paths(scr->get_path(), path)) {
  555. break;
  556. }
  557. for (int i = 0; i < current->get_child_count(); ++i) {
  558. stack.push_back(current->get_child(i));
  559. }
  560. }
  561. Ref<GDScript> scr = current->get_script();
  562. if (scr.is_null() || !GDScript::is_canonically_equal_paths(scr->get_path(), path)) {
  563. current = owner_scene_node;
  564. }
  565. }
  566. String code = parser->get_text_for_completion(p_params.position);
  567. GDScriptLanguage::get_singleton()->complete_code(code, path, current, r_options, forced, call_hint);
  568. if (owner_scene_node) {
  569. memdelete(owner_scene_node);
  570. }
  571. }
  572. }
  573. const LSP::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const LSP::TextDocumentPositionParams &p_doc_pos, const String &p_symbol_name, bool p_func_required) {
  574. const LSP::DocumentSymbol *symbol = nullptr;
  575. String path = get_file_path(p_doc_pos.textDocument.uri);
  576. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  577. String symbol_identifier = p_symbol_name;
  578. Vector<String> identifier_parts = symbol_identifier.split("(");
  579. if (identifier_parts.size()) {
  580. symbol_identifier = identifier_parts[0];
  581. }
  582. LSP::Position pos = p_doc_pos.position;
  583. if (symbol_identifier.is_empty()) {
  584. LSP::Range range;
  585. symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);
  586. pos.character = range.end.character;
  587. }
  588. if (!symbol_identifier.is_empty()) {
  589. if (ScriptServer::is_global_class(symbol_identifier)) {
  590. String class_path = ScriptServer::get_global_class_path(symbol_identifier);
  591. symbol = get_script_symbol(class_path);
  592. } else {
  593. ScriptLanguage::LookupResult ret;
  594. if (symbol_identifier == "new" && parser->get_lines()[p_doc_pos.position.line].remove_chars(" \t").contains("new(")) {
  595. symbol_identifier = "_init";
  596. }
  597. if (OK == GDScriptLanguage::get_singleton()->lookup_code(parser->get_text_for_lookup_symbol(pos, symbol_identifier, p_func_required), symbol_identifier, path, nullptr, ret)) {
  598. if (ret.location >= 0) {
  599. String target_script_path = path;
  600. if (ret.script.is_valid()) {
  601. target_script_path = ret.script->get_path();
  602. } else if (!ret.script_path.is_empty()) {
  603. target_script_path = ret.script_path;
  604. }
  605. if (const ExtendGDScriptParser *target_parser = get_parse_result(target_script_path)) {
  606. symbol = target_parser->get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(ret.location), symbol_identifier);
  607. if (symbol) {
  608. switch (symbol->kind) {
  609. case LSP::SymbolKind::Function: {
  610. if (symbol->name != symbol_identifier) {
  611. symbol = get_parameter_symbol(symbol, symbol_identifier);
  612. }
  613. } break;
  614. }
  615. }
  616. }
  617. } else {
  618. String member = ret.class_member;
  619. if (member.is_empty() && symbol_identifier != ret.class_name) {
  620. member = symbol_identifier;
  621. }
  622. symbol = get_native_symbol(ret.class_name, member);
  623. }
  624. } else {
  625. symbol = get_local_symbol_at(parser, symbol_identifier, p_doc_pos.position);
  626. if (!symbol) {
  627. symbol = parser->get_member_symbol(symbol_identifier);
  628. }
  629. }
  630. }
  631. }
  632. }
  633. return symbol;
  634. }
  635. void GDScriptWorkspace::resolve_related_symbols(const LSP::TextDocumentPositionParams &p_doc_pos, List<const LSP::DocumentSymbol *> &r_list) {
  636. String path = get_file_path(p_doc_pos.textDocument.uri);
  637. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  638. String symbol_identifier;
  639. LSP::Range range;
  640. symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);
  641. for (const KeyValue<StringName, ClassMembers> &E : native_members) {
  642. const ClassMembers &members = native_members.get(E.key);
  643. if (const LSP::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
  644. r_list.push_back(*symbol);
  645. }
  646. }
  647. for (const KeyValue<String, ExtendGDScriptParser *> &E : scripts) {
  648. const ExtendGDScriptParser *scr = E.value;
  649. const ClassMembers &members = scr->get_members();
  650. if (const LSP::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
  651. r_list.push_back(*symbol);
  652. }
  653. for (const KeyValue<String, ClassMembers> &F : scr->get_inner_classes()) {
  654. const ClassMembers *inner_class = &F.value;
  655. if (const LSP::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) {
  656. r_list.push_back(*symbol);
  657. }
  658. }
  659. }
  660. }
  661. }
  662. const LSP::DocumentSymbol *GDScriptWorkspace::resolve_native_symbol(const LSP::NativeSymbolInspectParams &p_params) {
  663. if (HashMap<StringName, LSP::DocumentSymbol>::Iterator E = native_symbols.find(p_params.native_class)) {
  664. const LSP::DocumentSymbol &symbol = E->value;
  665. if (p_params.symbol_name.is_empty() || p_params.symbol_name == symbol.name) {
  666. return &symbol;
  667. }
  668. for (int i = 0; i < symbol.children.size(); ++i) {
  669. if (symbol.children[i].name == p_params.symbol_name) {
  670. return &(symbol.children[i]);
  671. }
  672. }
  673. }
  674. return nullptr;
  675. }
  676. void GDScriptWorkspace::resolve_document_links(const String &p_uri, List<LSP::DocumentLink> &r_list) {
  677. if (const ExtendGDScriptParser *parser = get_parse_successed_script(get_file_path(p_uri))) {
  678. const List<LSP::DocumentLink> &links = parser->get_document_links();
  679. for (const LSP::DocumentLink &E : links) {
  680. r_list.push_back(E);
  681. }
  682. }
  683. }
  684. Dictionary GDScriptWorkspace::generate_script_api(const String &p_path) {
  685. Dictionary api;
  686. if (const ExtendGDScriptParser *parser = get_parse_successed_script(p_path)) {
  687. api = parser->generate_api();
  688. }
  689. return api;
  690. }
  691. Error GDScriptWorkspace::resolve_signature(const LSP::TextDocumentPositionParams &p_doc_pos, LSP::SignatureHelp &r_signature) {
  692. if (const ExtendGDScriptParser *parser = get_parse_result(get_file_path(p_doc_pos.textDocument.uri))) {
  693. LSP::TextDocumentPositionParams text_pos;
  694. text_pos.textDocument = p_doc_pos.textDocument;
  695. if (parser->get_left_function_call(p_doc_pos.position, text_pos.position, r_signature.activeParameter) == OK) {
  696. List<const LSP::DocumentSymbol *> symbols;
  697. if (const LSP::DocumentSymbol *symbol = resolve_symbol(text_pos)) {
  698. symbols.push_back(symbol);
  699. } else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
  700. GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_related_symbols(text_pos, symbols);
  701. }
  702. for (const LSP::DocumentSymbol *const &symbol : symbols) {
  703. if (symbol->kind == LSP::SymbolKind::Method || symbol->kind == LSP::SymbolKind::Function) {
  704. LSP::SignatureInformation signature_info;
  705. signature_info.label = symbol->detail;
  706. signature_info.documentation = symbol->render();
  707. for (int i = 0; i < symbol->children.size(); i++) {
  708. const LSP::DocumentSymbol &arg = symbol->children[i];
  709. LSP::ParameterInformation arg_info;
  710. arg_info.label = arg.name;
  711. signature_info.parameters.push_back(arg_info);
  712. }
  713. r_signature.signatures.push_back(signature_info);
  714. break;
  715. }
  716. }
  717. if (r_signature.signatures.size()) {
  718. return OK;
  719. }
  720. }
  721. }
  722. return ERR_METHOD_NOT_FOUND;
  723. }
  724. GDScriptWorkspace::GDScriptWorkspace() {}
  725. GDScriptWorkspace::~GDScriptWorkspace() {
  726. HashSet<String> cached_parsers;
  727. for (const KeyValue<String, ExtendGDScriptParser *> &E : parse_results) {
  728. cached_parsers.insert(E.key);
  729. }
  730. for (const KeyValue<String, ExtendGDScriptParser *> &E : scripts) {
  731. cached_parsers.insert(E.key);
  732. }
  733. for (const String &E : cached_parsers) {
  734. remove_cache_parser(E);
  735. }
  736. }