gdscript_workspace.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  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) {
  479. int port;
  480. String scheme;
  481. String host;
  482. String encoded_path;
  483. String fragment;
  484. // Don't use the returned error, the result isn't OK for URIs that are not valid web URLs.
  485. p_uri.parse_url(scheme, host, port, encoded_path, fragment);
  486. // TODO: Make the parsing RFC-3986 compliant.
  487. ERR_FAIL_COND_V_MSG(scheme != "file" && scheme != "file:" && scheme != "file://", String(), "LSP: The language server only supports the file protocol: " + p_uri);
  488. // Treat host like authority for now and ignore the port. It's an edge case for invalid file URI's anyway.
  489. ERR_FAIL_COND_V_MSG(host != "" && host != "localhost", String(), "LSP: The language server does not support nonlocal files: " + p_uri);
  490. // If query or fragment are present, the URI is not a valid file URI as per RFC-8089.
  491. // We currently don't handle the query and it will be part of the path. However,
  492. // this should not be a problem for a correct file URI.
  493. ERR_FAIL_COND_V_MSG(fragment != "", String(), "LSP: Received malformed file URI: " + p_uri);
  494. String canonical_res = ProjectSettings::get_singleton()->get_resource_path();
  495. String simple_path = encoded_path.uri_file_decode().simplify_path();
  496. // First try known paths that point to res://, to reduce file system interaction.
  497. bool res_adjusted = false;
  498. for (const String &res_path : absolute_res_paths) {
  499. if (simple_path.begins_with(res_path)) {
  500. res_adjusted = true;
  501. simple_path = "res://" + simple_path.substr(res_path.size());
  502. break;
  503. }
  504. }
  505. // Traverse the path and compare each directory with res://
  506. if (!res_adjusted) {
  507. Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
  508. int offset = 0;
  509. while (offset <= simple_path.length()) {
  510. offset = simple_path.find_char('/', offset);
  511. if (offset == -1) {
  512. offset = simple_path.length();
  513. }
  514. String part = simple_path.substr(0, offset);
  515. if (!part.is_empty()) {
  516. bool is_equal = dir->is_equivalent(canonical_res, part);
  517. if (is_equal) {
  518. absolute_res_paths.insert(part);
  519. res_adjusted = true;
  520. simple_path = "res://" + simple_path.substr(offset + 1);
  521. break;
  522. }
  523. }
  524. offset += 1;
  525. }
  526. // Could not resolve the path to the project.
  527. if (!res_adjusted) {
  528. return simple_path;
  529. }
  530. }
  531. // Resolve the file inside of the project using EditorFileSystem.
  532. EditorFileSystemDirectory *editor_dir;
  533. int file_idx;
  534. editor_dir = EditorFileSystem::get_singleton()->find_file(simple_path, &file_idx);
  535. if (editor_dir) {
  536. return editor_dir->get_file_path(file_idx);
  537. }
  538. return simple_path;
  539. }
  540. String GDScriptWorkspace::get_file_uri(const String &p_path) const {
  541. String path = ProjectSettings::get_singleton()->globalize_path(p_path).lstrip("/");
  542. LocalVector<String> encoded_parts;
  543. for (const String &part : path.split("/")) {
  544. encoded_parts.push_back(part.uri_encode());
  545. }
  546. // Always return file URI's with authority part (encoding drive letters with leading slash), to maintain compat with RFC-1738 which required it.
  547. return "file:///" + String("/").join(encoded_parts);
  548. }
  549. void GDScriptWorkspace::publish_diagnostics(const String &p_path) {
  550. Dictionary params;
  551. Array errors;
  552. HashMap<String, ExtendGDScriptParser *>::ConstIterator ele = parse_results.find(p_path);
  553. if (ele) {
  554. const Vector<LSP::Diagnostic> &list = ele->value->get_diagnostics();
  555. errors.resize(list.size());
  556. for (int i = 0; i < list.size(); ++i) {
  557. errors[i] = list[i].to_json();
  558. }
  559. }
  560. params["diagnostics"] = errors;
  561. params["uri"] = get_file_uri(p_path);
  562. GDScriptLanguageProtocol::get_singleton()->notify_client("textDocument/publishDiagnostics", params);
  563. }
  564. void GDScriptWorkspace::_get_owners(EditorFileSystemDirectory *efsd, String p_path, List<String> &owners) {
  565. if (!efsd) {
  566. return;
  567. }
  568. for (int i = 0; i < efsd->get_subdir_count(); i++) {
  569. _get_owners(efsd->get_subdir(i), p_path, owners);
  570. }
  571. for (int i = 0; i < efsd->get_file_count(); i++) {
  572. Vector<String> deps = efsd->get_file_deps(i);
  573. bool found = false;
  574. for (int j = 0; j < deps.size(); j++) {
  575. if (deps[j] == p_path) {
  576. found = true;
  577. break;
  578. }
  579. }
  580. if (!found) {
  581. continue;
  582. }
  583. owners.push_back(efsd->get_file_path(i));
  584. }
  585. }
  586. Node *GDScriptWorkspace::_get_owner_scene_node(String p_path) {
  587. Node *owner_scene_node = nullptr;
  588. List<String> owners;
  589. _get_owners(EditorFileSystem::get_singleton()->get_filesystem(), p_path, owners);
  590. for (const String &owner : owners) {
  591. NodePath owner_path = owner;
  592. Ref<Resource> owner_res = ResourceLoader::load(String(owner_path));
  593. if (Object::cast_to<PackedScene>(owner_res.ptr())) {
  594. Ref<PackedScene> owner_packed_scene = Ref<PackedScene>(Object::cast_to<PackedScene>(*owner_res));
  595. owner_scene_node = owner_packed_scene->instantiate();
  596. break;
  597. }
  598. }
  599. return owner_scene_node;
  600. }
  601. void GDScriptWorkspace::completion(const LSP::CompletionParams &p_params, List<ScriptLanguage::CodeCompletionOption> *r_options) {
  602. String path = get_file_path(p_params.textDocument.uri);
  603. String call_hint;
  604. bool forced = false;
  605. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  606. Node *owner_scene_node = _get_owner_scene_node(path);
  607. Array stack;
  608. Node *current = nullptr;
  609. if (owner_scene_node != nullptr) {
  610. stack.push_back(owner_scene_node);
  611. while (!stack.is_empty()) {
  612. current = Object::cast_to<Node>(stack.pop_back());
  613. Ref<GDScript> scr = current->get_script();
  614. if (scr.is_valid() && GDScript::is_canonically_equal_paths(scr->get_path(), path)) {
  615. break;
  616. }
  617. for (int i = 0; i < current->get_child_count(); ++i) {
  618. stack.push_back(current->get_child(i));
  619. }
  620. }
  621. Ref<GDScript> scr = current->get_script();
  622. if (scr.is_null() || !GDScript::is_canonically_equal_paths(scr->get_path(), path)) {
  623. current = owner_scene_node;
  624. }
  625. }
  626. String code = parser->get_text_for_completion(p_params.position);
  627. GDScriptLanguage::get_singleton()->complete_code(code, path, current, r_options, forced, call_hint);
  628. if (owner_scene_node) {
  629. memdelete(owner_scene_node);
  630. }
  631. }
  632. }
  633. const LSP::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const LSP::TextDocumentPositionParams &p_doc_pos, const String &p_symbol_name, bool p_func_required) {
  634. const LSP::DocumentSymbol *symbol = nullptr;
  635. String path = get_file_path(p_doc_pos.textDocument.uri);
  636. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  637. String symbol_identifier = p_symbol_name;
  638. Vector<String> identifier_parts = symbol_identifier.split("(");
  639. if (identifier_parts.size()) {
  640. symbol_identifier = identifier_parts[0];
  641. }
  642. LSP::Position pos = p_doc_pos.position;
  643. if (symbol_identifier.is_empty()) {
  644. LSP::Range range;
  645. symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);
  646. pos.character = range.end.character;
  647. }
  648. if (!symbol_identifier.is_empty()) {
  649. if (ScriptServer::is_global_class(symbol_identifier)) {
  650. String class_path = ScriptServer::get_global_class_path(symbol_identifier);
  651. symbol = get_script_symbol(class_path);
  652. } else {
  653. ScriptLanguage::LookupResult ret;
  654. if (symbol_identifier == "new" && parser->get_lines()[p_doc_pos.position.line].remove_chars(" \t").contains("new(")) {
  655. symbol_identifier = "_init";
  656. }
  657. if (OK == GDScriptLanguage::get_singleton()->lookup_code(parser->get_text_for_lookup_symbol(pos, symbol_identifier, p_func_required), symbol_identifier, path, nullptr, ret)) {
  658. if (ret.location >= 0) {
  659. String target_script_path = path;
  660. if (ret.script.is_valid()) {
  661. target_script_path = ret.script->get_path();
  662. } else if (!ret.script_path.is_empty()) {
  663. target_script_path = ret.script_path;
  664. }
  665. if (const ExtendGDScriptParser *target_parser = get_parse_result(target_script_path)) {
  666. symbol = target_parser->get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(ret.location), symbol_identifier);
  667. if (symbol) {
  668. switch (symbol->kind) {
  669. case LSP::SymbolKind::Function: {
  670. if (symbol->name != symbol_identifier) {
  671. symbol = get_parameter_symbol(symbol, symbol_identifier);
  672. }
  673. } break;
  674. }
  675. }
  676. }
  677. } else {
  678. String member = ret.class_member;
  679. if (member.is_empty() && symbol_identifier != ret.class_name) {
  680. member = symbol_identifier;
  681. }
  682. symbol = get_native_symbol(ret.class_name, member);
  683. }
  684. } else {
  685. symbol = get_local_symbol_at(parser, symbol_identifier, p_doc_pos.position);
  686. if (!symbol) {
  687. symbol = parser->get_member_symbol(symbol_identifier);
  688. }
  689. }
  690. }
  691. }
  692. }
  693. return symbol;
  694. }
  695. void GDScriptWorkspace::resolve_related_symbols(const LSP::TextDocumentPositionParams &p_doc_pos, List<const LSP::DocumentSymbol *> &r_list) {
  696. String path = get_file_path(p_doc_pos.textDocument.uri);
  697. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  698. String symbol_identifier;
  699. LSP::Range range;
  700. symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, range);
  701. for (const KeyValue<StringName, ClassMembers> &E : native_members) {
  702. const ClassMembers &members = native_members.get(E.key);
  703. if (const LSP::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
  704. r_list.push_back(*symbol);
  705. }
  706. }
  707. for (const KeyValue<String, ExtendGDScriptParser *> &E : scripts) {
  708. const ExtendGDScriptParser *scr = E.value;
  709. const ClassMembers &members = scr->get_members();
  710. if (const LSP::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
  711. r_list.push_back(*symbol);
  712. }
  713. for (const KeyValue<String, ClassMembers> &F : scr->get_inner_classes()) {
  714. const ClassMembers *inner_class = &F.value;
  715. if (const LSP::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) {
  716. r_list.push_back(*symbol);
  717. }
  718. }
  719. }
  720. }
  721. }
  722. const LSP::DocumentSymbol *GDScriptWorkspace::resolve_native_symbol(const LSP::NativeSymbolInspectParams &p_params) {
  723. if (HashMap<StringName, LSP::DocumentSymbol>::Iterator E = native_symbols.find(p_params.native_class)) {
  724. const LSP::DocumentSymbol &symbol = E->value;
  725. if (p_params.symbol_name.is_empty() || p_params.symbol_name == symbol.name) {
  726. return &symbol;
  727. }
  728. for (int i = 0; i < symbol.children.size(); ++i) {
  729. if (symbol.children[i].name == p_params.symbol_name) {
  730. return &(symbol.children[i]);
  731. }
  732. }
  733. }
  734. return nullptr;
  735. }
  736. void GDScriptWorkspace::resolve_document_links(const String &p_uri, List<LSP::DocumentLink> &r_list) {
  737. if (const ExtendGDScriptParser *parser = get_parse_successed_script(get_file_path(p_uri))) {
  738. const List<LSP::DocumentLink> &links = parser->get_document_links();
  739. for (const LSP::DocumentLink &E : links) {
  740. r_list.push_back(E);
  741. }
  742. }
  743. }
  744. Dictionary GDScriptWorkspace::generate_script_api(const String &p_path) {
  745. Dictionary api;
  746. if (const ExtendGDScriptParser *parser = get_parse_successed_script(p_path)) {
  747. api = parser->generate_api();
  748. }
  749. return api;
  750. }
  751. Error GDScriptWorkspace::resolve_signature(const LSP::TextDocumentPositionParams &p_doc_pos, LSP::SignatureHelp &r_signature) {
  752. if (const ExtendGDScriptParser *parser = get_parse_result(get_file_path(p_doc_pos.textDocument.uri))) {
  753. LSP::TextDocumentPositionParams text_pos;
  754. text_pos.textDocument = p_doc_pos.textDocument;
  755. if (parser->get_left_function_call(p_doc_pos.position, text_pos.position, r_signature.activeParameter) == OK) {
  756. List<const LSP::DocumentSymbol *> symbols;
  757. if (const LSP::DocumentSymbol *symbol = resolve_symbol(text_pos)) {
  758. symbols.push_back(symbol);
  759. } else if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
  760. GDScriptLanguageProtocol::get_singleton()->get_workspace()->resolve_related_symbols(text_pos, symbols);
  761. }
  762. for (const LSP::DocumentSymbol *const &symbol : symbols) {
  763. if (symbol->kind == LSP::SymbolKind::Method || symbol->kind == LSP::SymbolKind::Function) {
  764. LSP::SignatureInformation signature_info;
  765. signature_info.label = symbol->detail;
  766. signature_info.documentation = symbol->render();
  767. for (int i = 0; i < symbol->children.size(); i++) {
  768. const LSP::DocumentSymbol &arg = symbol->children[i];
  769. LSP::ParameterInformation arg_info;
  770. arg_info.label = arg.name;
  771. signature_info.parameters.push_back(arg_info);
  772. }
  773. r_signature.signatures.push_back(signature_info);
  774. break;
  775. }
  776. }
  777. if (r_signature.signatures.size()) {
  778. return OK;
  779. }
  780. }
  781. }
  782. return ERR_METHOD_NOT_FOUND;
  783. }
  784. GDScriptWorkspace::GDScriptWorkspace() {}
  785. GDScriptWorkspace::~GDScriptWorkspace() {
  786. HashSet<String> cached_parsers;
  787. for (const KeyValue<String, ExtendGDScriptParser *> &E : parse_results) {
  788. cached_parsers.insert(E.key);
  789. }
  790. for (const KeyValue<String, ExtendGDScriptParser *> &E : scripts) {
  791. cached_parsers.insert(E.key);
  792. }
  793. for (const String &E : cached_parsers) {
  794. remove_cache_parser(E);
  795. }
  796. }