gdscript_workspace.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. /*************************************************************************/
  2. /* gdscript_workspace.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 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_workspace.h"
  31. #include "../gdscript.h"
  32. #include "../gdscript_parser.h"
  33. #include "core/project_settings.h"
  34. #include "core/script_language.h"
  35. #include "editor/editor_help.h"
  36. #include "gdscript_language_protocol.h"
  37. void GDScriptWorkspace::_bind_methods() {
  38. ClassDB::bind_method(D_METHOD("symbol"), &GDScriptWorkspace::symbol);
  39. }
  40. void GDScriptWorkspace::remove_cache_parser(const String &p_path) {
  41. Map<String, ExtendGDScriptParser *>::Element *parser = parse_results.find(p_path);
  42. Map<String, ExtendGDScriptParser *>::Element *script = scripts.find(p_path);
  43. if (parser && script) {
  44. if (script->get() && script->get() == script->get()) {
  45. memdelete(script->get());
  46. } else {
  47. memdelete(script->get());
  48. memdelete(parser->get());
  49. }
  50. parse_results.erase(p_path);
  51. scripts.erase(p_path);
  52. } else if (parser) {
  53. memdelete(parser->get());
  54. parse_results.erase(p_path);
  55. } else if (script) {
  56. memdelete(script->get());
  57. scripts.erase(p_path);
  58. }
  59. }
  60. const lsp::DocumentSymbol *GDScriptWorkspace::get_native_symbol(const String &p_class, const String &p_member) const {
  61. StringName class_name = p_class;
  62. StringName empty;
  63. while (class_name != empty) {
  64. if (const Map<StringName, lsp::DocumentSymbol>::Element *E = native_symbols.find(class_name)) {
  65. const lsp::DocumentSymbol &class_symbol = E->value();
  66. if (p_member.empty()) {
  67. return &class_symbol;
  68. } else {
  69. for (int i = 0; i < class_symbol.children.size(); i++) {
  70. const lsp::DocumentSymbol &symbol = class_symbol.children[i];
  71. if (symbol.name == p_member) {
  72. return &symbol;
  73. }
  74. }
  75. }
  76. }
  77. class_name = ClassDB::get_parent_class(class_name);
  78. }
  79. return NULL;
  80. }
  81. const lsp::DocumentSymbol *GDScriptWorkspace::get_script_symbol(const String &p_path) const {
  82. const Map<String, ExtendGDScriptParser *>::Element *S = scripts.find(p_path);
  83. if (S) {
  84. return &(S->get()->get_symbols());
  85. }
  86. return NULL;
  87. }
  88. void GDScriptWorkspace::reload_all_workspace_scripts() {
  89. List<String> pathes;
  90. list_script_files("res://", pathes);
  91. for (List<String>::Element *E = pathes.front(); E; E = E->next()) {
  92. const String &path = E->get();
  93. Error err;
  94. String content = FileAccess::get_file_as_string(path, &err);
  95. ERR_CONTINUE(err != OK);
  96. err = parse_script(path, content);
  97. if (err != OK) {
  98. Map<String, ExtendGDScriptParser *>::Element *S = parse_results.find(path);
  99. String err_msg = "Failed parse script " + path;
  100. if (S) {
  101. err_msg += "\n" + S->get()->get_error();
  102. }
  103. ERR_EXPLAIN(err_msg);
  104. ERR_CONTINUE(err != OK);
  105. }
  106. }
  107. }
  108. void GDScriptWorkspace::list_script_files(const String &p_root_dir, List<String> &r_files) {
  109. Error err;
  110. DirAccessRef dir = DirAccess::open(p_root_dir, &err);
  111. if (OK == err) {
  112. dir->list_dir_begin();
  113. String file_name = dir->get_next();
  114. while (file_name.length()) {
  115. if (dir->current_is_dir() && file_name != "." && file_name != ".." && file_name != "./") {
  116. list_script_files(p_root_dir.plus_file(file_name), r_files);
  117. } else if (file_name.ends_with(".gd")) {
  118. String script_file = p_root_dir.plus_file(file_name);
  119. r_files.push_back(script_file);
  120. }
  121. file_name = dir->get_next();
  122. }
  123. }
  124. }
  125. ExtendGDScriptParser *GDScriptWorkspace::get_parse_successed_script(const String &p_path) {
  126. const Map<String, ExtendGDScriptParser *>::Element *S = scripts.find(p_path);
  127. if (!S) {
  128. parse_local_script(p_path);
  129. S = scripts.find(p_path);
  130. }
  131. if (S) {
  132. return S->get();
  133. }
  134. return NULL;
  135. }
  136. ExtendGDScriptParser *GDScriptWorkspace::get_parse_result(const String &p_path) {
  137. const Map<String, ExtendGDScriptParser *>::Element *S = parse_results.find(p_path);
  138. if (!S) {
  139. parse_local_script(p_path);
  140. S = parse_results.find(p_path);
  141. }
  142. if (S) {
  143. return S->get();
  144. }
  145. return NULL;
  146. }
  147. String GDScriptWorkspace::marked_documentation(const String &p_bbcode) {
  148. String markdown = p_bbcode.strip_edges();
  149. Vector<String> lines = markdown.split("\n");
  150. bool in_code_block = false;
  151. int code_block_indent = -1;
  152. markdown = "";
  153. for (int i = 0; i < lines.size(); i++) {
  154. String line = lines[i];
  155. int block_start = line.find("[codeblock]");
  156. if (block_start != -1) {
  157. code_block_indent = block_start;
  158. in_code_block = true;
  159. line = "'''gdscript";
  160. line = "\n";
  161. } else if (in_code_block) {
  162. line = "\t" + line.substr(code_block_indent, line.length());
  163. }
  164. if (in_code_block && line.find("[/codeblock]") != -1) {
  165. line = "'''\n";
  166. line = "\n";
  167. in_code_block = false;
  168. }
  169. if (!in_code_block) {
  170. line = line.strip_edges();
  171. line = line.replace("[code]", "`");
  172. line = line.replace("[/code]", "`");
  173. line = line.replace("[i]", "*");
  174. line = line.replace("[/i]", "*");
  175. line = line.replace("[b]", "**");
  176. line = line.replace("[/b]", "**");
  177. line = line.replace("[u]", "__");
  178. line = line.replace("[/u]", "__");
  179. line = line.replace("[method ", "`");
  180. line = line.replace("[member ", "`");
  181. line = line.replace("[signal ", "`");
  182. line = line.replace("[", "`");
  183. line = line.replace("]", "`");
  184. }
  185. if (!in_code_block && i < lines.size() - 1) {
  186. line += "\n";
  187. }
  188. markdown += line + "\n";
  189. }
  190. return markdown;
  191. }
  192. Array GDScriptWorkspace::symbol(const Dictionary &p_params) {
  193. String query = p_params["query"];
  194. Array arr;
  195. if (!query.empty()) {
  196. for (Map<String, ExtendGDScriptParser *>::Element *E = scripts.front(); E; E = E->next()) {
  197. Vector<lsp::DocumentedSymbolInformation> script_symbols;
  198. E->get()->get_symbols().symbol_tree_as_list(E->key(), script_symbols);
  199. for (int i = 0; i < script_symbols.size(); ++i) {
  200. if (query.is_subsequence_ofi(script_symbols[i].name)) {
  201. arr.push_back(script_symbols[i].to_json());
  202. }
  203. }
  204. }
  205. }
  206. return arr;
  207. }
  208. Error GDScriptWorkspace::initialize() {
  209. if (initialized) return OK;
  210. DocData *doc = EditorHelp::get_doc_data();
  211. for (Map<String, DocData::ClassDoc>::Element *E = doc->class_list.front(); E; E = E->next()) {
  212. const DocData::ClassDoc &class_data = E->value();
  213. lsp::DocumentSymbol class_symbol;
  214. String class_name = E->key();
  215. class_symbol.name = class_name;
  216. class_symbol.kind = lsp::SymbolKind::Class;
  217. class_symbol.detail = String("<Native> class ") + class_name;
  218. if (!class_data.inherits.empty()) {
  219. class_symbol.detail += " extends " + class_data.inherits;
  220. }
  221. class_symbol.documentation = marked_documentation(class_data.brief_description) + "\n" + marked_documentation(class_data.description);
  222. for (int i = 0; i < class_data.constants.size(); i++) {
  223. const DocData::ConstantDoc &const_data = class_data.constants[i];
  224. lsp::DocumentSymbol symbol;
  225. symbol.name = const_data.name;
  226. symbol.kind = lsp::SymbolKind::Constant;
  227. symbol.detail = "const " + class_name + "." + const_data.name;
  228. if (const_data.enumeration.length()) {
  229. symbol.detail += ": " + const_data.enumeration;
  230. }
  231. symbol.detail += " = " + const_data.value;
  232. symbol.documentation = marked_documentation(const_data.description);
  233. class_symbol.children.push_back(symbol);
  234. }
  235. Vector<DocData::PropertyDoc> properties;
  236. properties.append_array(class_data.properties);
  237. const int theme_prop_start_idx = properties.size();
  238. properties.append_array(class_data.theme_properties);
  239. for (int i = 0; i < class_data.properties.size(); i++) {
  240. const DocData::PropertyDoc &data = class_data.properties[i];
  241. lsp::DocumentSymbol symbol;
  242. symbol.name = data.name;
  243. symbol.kind = lsp::SymbolKind::Property;
  244. symbol.detail = String(i >= theme_prop_start_idx ? "<Theme> var" : "var") + " " + class_name + "." + data.name;
  245. if (data.enumeration.length()) {
  246. symbol.detail += ": " + data.enumeration;
  247. } else {
  248. symbol.detail += ": " + data.type;
  249. }
  250. symbol.documentation = marked_documentation(data.description);
  251. class_symbol.children.push_back(symbol);
  252. }
  253. Vector<DocData::MethodDoc> methods_signals;
  254. methods_signals.append_array(class_data.methods);
  255. const int signal_start_idx = methods_signals.size();
  256. methods_signals.append_array(class_data.signals);
  257. for (int i = 0; i < methods_signals.size(); i++) {
  258. const DocData::MethodDoc &data = methods_signals[i];
  259. lsp::DocumentSymbol symbol;
  260. symbol.name = data.name;
  261. symbol.kind = i >= signal_start_idx ? lsp::SymbolKind::Event : lsp::SymbolKind::Method;
  262. String params = "";
  263. bool arg_default_value_started = false;
  264. for (int j = 0; j < data.arguments.size(); j++) {
  265. const DocData::ArgumentDoc &arg = data.arguments[j];
  266. if (!arg_default_value_started && !arg.default_value.empty()) {
  267. arg_default_value_started = true;
  268. }
  269. String arg_str = arg.name + ": " + arg.type;
  270. if (arg_default_value_started) {
  271. arg_str += " = " + arg.default_value;
  272. }
  273. if (j < data.arguments.size() - 1) {
  274. arg_str += ", ";
  275. }
  276. params += arg_str;
  277. }
  278. if (data.qualifiers.find("vararg") != -1) {
  279. params += params.empty() ? "..." : ", ...";
  280. }
  281. symbol.detail = "func " + class_name + "." + data.name + "(" + params + ") -> " + data.return_type;
  282. symbol.documentation = marked_documentation(data.description);
  283. class_symbol.children.push_back(symbol);
  284. }
  285. native_symbols.insert(class_name, class_symbol);
  286. }
  287. reload_all_workspace_scripts();
  288. if (GDScriptLanguageProtocol::get_singleton()->is_smart_resolve_enabled()) {
  289. for (Map<StringName, lsp::DocumentSymbol>::Element *E = native_symbols.front(); E; E = E->next()) {
  290. ClassMembers members;
  291. const lsp::DocumentSymbol &class_symbol = E->get();
  292. for (int i = 0; i < class_symbol.children.size(); i++) {
  293. const lsp::DocumentSymbol &symbol = class_symbol.children[i];
  294. members.set(symbol.name, &symbol);
  295. }
  296. native_members.set(E->key(), members);
  297. }
  298. // cache member completions
  299. for (Map<String, ExtendGDScriptParser *>::Element *S = scripts.front(); S; S = S->next()) {
  300. S->get()->get_member_completions();
  301. }
  302. }
  303. return OK;
  304. }
  305. Error GDScriptWorkspace::parse_script(const String &p_path, const String &p_content) {
  306. ExtendGDScriptParser *parser = memnew(ExtendGDScriptParser);
  307. Error err = parser->parse(p_content, p_path);
  308. Map<String, ExtendGDScriptParser *>::Element *last_parser = parse_results.find(p_path);
  309. Map<String, ExtendGDScriptParser *>::Element *last_script = scripts.find(p_path);
  310. if (err == OK) {
  311. remove_cache_parser(p_path);
  312. parse_results[p_path] = parser;
  313. scripts[p_path] = parser;
  314. } else {
  315. if (last_parser && last_script && last_parser->get() != last_script->get()) {
  316. memdelete(last_parser->get());
  317. }
  318. parse_results[p_path] = parser;
  319. }
  320. publish_diagnostics(p_path);
  321. return err;
  322. }
  323. Error GDScriptWorkspace::parse_local_script(const String &p_path) {
  324. Error err;
  325. String content = FileAccess::get_file_as_string(p_path, &err);
  326. if (err == OK) {
  327. err = parse_script(p_path, content);
  328. }
  329. return err;
  330. }
  331. String GDScriptWorkspace::get_file_path(const String &p_uri) const {
  332. String path = p_uri;
  333. path = path.replace(root_uri + "/", "res://");
  334. path = path.http_unescape();
  335. return path;
  336. }
  337. String GDScriptWorkspace::get_file_uri(const String &p_path) const {
  338. String uri = p_path;
  339. uri = uri.replace("res://", root_uri + "/");
  340. return uri;
  341. }
  342. void GDScriptWorkspace::publish_diagnostics(const String &p_path) {
  343. Dictionary params;
  344. Array errors;
  345. const Map<String, ExtendGDScriptParser *>::Element *ele = parse_results.find(p_path);
  346. if (ele) {
  347. const Vector<lsp::Diagnostic> &list = ele->get()->get_diagnostics();
  348. errors.resize(list.size());
  349. for (int i = 0; i < list.size(); ++i) {
  350. errors[i] = list[i].to_json();
  351. }
  352. }
  353. params["diagnostics"] = errors;
  354. params["uri"] = get_file_uri(p_path);
  355. GDScriptLanguageProtocol::get_singleton()->notify_client("textDocument/publishDiagnostics", params);
  356. }
  357. void GDScriptWorkspace::completion(const lsp::CompletionParams &p_params, List<ScriptCodeCompletionOption> *r_options) {
  358. String path = get_file_path(p_params.textDocument.uri);
  359. String call_hint;
  360. bool forced = false;
  361. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  362. String code = parser->get_text_for_completion(p_params.position);
  363. GDScriptLanguage::get_singleton()->complete_code(code, path, NULL, r_options, forced, call_hint);
  364. }
  365. }
  366. const lsp::DocumentSymbol *GDScriptWorkspace::resolve_symbol(const lsp::TextDocumentPositionParams &p_doc_pos, const String &p_symbol_name, bool p_func_requred) {
  367. const lsp::DocumentSymbol *symbol = NULL;
  368. String path = get_file_path(p_doc_pos.textDocument.uri);
  369. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  370. String symbol_identifier = p_symbol_name;
  371. lsp::Position pos = p_doc_pos.position;
  372. if (symbol_identifier.empty()) {
  373. Vector2i offset;
  374. symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, offset);
  375. pos.character += offset.y;
  376. }
  377. if (!symbol_identifier.empty()) {
  378. if (ScriptServer::is_global_class(symbol_identifier)) {
  379. String class_path = ScriptServer::get_global_class_path(symbol_identifier);
  380. symbol = get_script_symbol(class_path);
  381. } else {
  382. ScriptLanguage::LookupResult ret;
  383. if (OK == GDScriptLanguage::get_singleton()->lookup_code(parser->get_text_for_lookup_symbol(pos, symbol_identifier, p_func_requred), symbol_identifier, path, NULL, ret)) {
  384. if (ret.type == ScriptLanguage::LookupResult::RESULT_SCRIPT_LOCATION) {
  385. String target_script_path = path;
  386. if (!ret.script.is_null()) {
  387. target_script_path = ret.script->get_path();
  388. }
  389. if (const ExtendGDScriptParser *target_parser = get_parse_result(target_script_path)) {
  390. symbol = target_parser->get_symbol_defined_at_line(LINE_NUMBER_TO_INDEX(ret.location));
  391. }
  392. } else {
  393. String member = ret.class_member;
  394. if (member.empty() && symbol_identifier != ret.class_name) {
  395. member = symbol_identifier;
  396. }
  397. symbol = get_native_symbol(ret.class_name, member);
  398. }
  399. } else {
  400. symbol = parser->get_member_symbol(symbol_identifier);
  401. }
  402. }
  403. }
  404. }
  405. return symbol;
  406. }
  407. void GDScriptWorkspace::resolve_related_symbols(const lsp::TextDocumentPositionParams &p_doc_pos, List<const lsp::DocumentSymbol *> &r_list) {
  408. String path = get_file_path(p_doc_pos.textDocument.uri);
  409. if (const ExtendGDScriptParser *parser = get_parse_result(path)) {
  410. String symbol_identifier;
  411. Vector2i offset;
  412. symbol_identifier = parser->get_identifier_under_position(p_doc_pos.position, offset);
  413. const StringName *class_ptr = native_members.next(NULL);
  414. while (class_ptr) {
  415. const ClassMembers &members = native_members.get(*class_ptr);
  416. if (const lsp::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
  417. r_list.push_back(*symbol);
  418. }
  419. class_ptr = native_members.next(class_ptr);
  420. }
  421. for (Map<String, ExtendGDScriptParser *>::Element *E = scripts.front(); E; E = E->next()) {
  422. const ExtendGDScriptParser *script = E->get();
  423. const ClassMembers &members = script->get_members();
  424. if (const lsp::DocumentSymbol *const *symbol = members.getptr(symbol_identifier)) {
  425. r_list.push_back(*symbol);
  426. }
  427. const HashMap<String, ClassMembers> &inner_classes = script->get_inner_classes();
  428. const String *_class = inner_classes.next(NULL);
  429. while (_class) {
  430. const ClassMembers *inner_class = inner_classes.getptr(*_class);
  431. if (const lsp::DocumentSymbol *const *symbol = inner_class->getptr(symbol_identifier)) {
  432. r_list.push_back(*symbol);
  433. }
  434. _class = inner_classes.next(_class);
  435. }
  436. }
  437. }
  438. }
  439. GDScriptWorkspace::GDScriptWorkspace() {
  440. ProjectSettings::get_singleton()->get_resource_path();
  441. }
  442. GDScriptWorkspace::~GDScriptWorkspace() {
  443. Set<String> cached_parsers;
  444. for (Map<String, ExtendGDScriptParser *>::Element *E = parse_results.front(); E; E = E->next()) {
  445. cached_parsers.insert(E->key());
  446. }
  447. for (Map<String, ExtendGDScriptParser *>::Element *E = scripts.front(); E; E = E->next()) {
  448. cached_parsers.insert(E->key());
  449. }
  450. for (Set<String>::Element *E = cached_parsers.front(); E; E = E->next()) {
  451. remove_cache_parser(E->get());
  452. }
  453. }