gdscript_editor.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. /*************************************************************************/
  2. /* gdscript_editor.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #include "gdscript.h"
  31. #include "core/engine.h"
  32. #include "core/global_constants.h"
  33. #include "core/os/file_access.h"
  34. #include "gdscript_compiler.h"
  35. #include "gdscript_parser.h"
  36. #include "gdscript_tokenizer.h"
  37. #ifdef TOOLS_ENABLED
  38. #include "editor/editor_file_system.h"
  39. #include "editor/editor_settings.h"
  40. #endif
  41. void GDScriptLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
  42. p_delimiters->push_back("#");
  43. }
  44. void GDScriptLanguage::get_string_delimiters(List<String> *p_delimiters) const {
  45. p_delimiters->push_back("\" \"");
  46. p_delimiters->push_back("' '");
  47. p_delimiters->push_back("\"\"\" \"\"\"");
  48. }
  49. String GDScriptLanguage::_get_processed_template(const String &p_template, const String &p_base_class_name) const {
  50. String processed_template = p_template;
  51. #ifdef TOOLS_ENABLED
  52. if (EDITOR_DEF("text_editor/completion/add_type_hints", false)) {
  53. processed_template = processed_template.replace("%INT_TYPE%", ": int");
  54. processed_template = processed_template.replace("%STRING_TYPE%", ": String");
  55. processed_template = processed_template.replace("%FLOAT_TYPE%", ": float");
  56. processed_template = processed_template.replace("%VOID_RETURN%", " -> void");
  57. } else {
  58. processed_template = processed_template.replace("%INT_TYPE%", "");
  59. processed_template = processed_template.replace("%STRING_TYPE%", "");
  60. processed_template = processed_template.replace("%FLOAT_TYPE%", "");
  61. processed_template = processed_template.replace("%VOID_RETURN%", "");
  62. }
  63. #else
  64. processed_template = processed_template.replace("%INT_TYPE%", "");
  65. processed_template = processed_template.replace("%STRING_TYPE%", "");
  66. processed_template = processed_template.replace("%FLOAT_TYPE%", "");
  67. processed_template = processed_template.replace("%VOID_RETURN%", "");
  68. #endif
  69. processed_template = processed_template.replace("%BASE%", p_base_class_name);
  70. processed_template = processed_template.replace("%TS%", _get_indentation());
  71. return processed_template;
  72. }
  73. Ref<Script> GDScriptLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const {
  74. String _template = "extends %BASE%\n"
  75. "\n"
  76. "\n"
  77. "# Declare member variables here. Examples:\n"
  78. "# var a%INT_TYPE% = 2\n"
  79. "# var b%STRING_TYPE% = \"text\"\n"
  80. "\n"
  81. "\n"
  82. "# Called when the node enters the scene tree for the first time.\n"
  83. "func _ready()%VOID_RETURN%:\n"
  84. "%TS%pass # Replace with function body.\n"
  85. "\n"
  86. "\n"
  87. "# Called every frame. 'delta' is the elapsed time since the previous frame.\n"
  88. "#func _process(delta%FLOAT_TYPE%)%VOID_RETURN%:\n"
  89. "#%TS%pass\n";
  90. _template = _get_processed_template(_template, p_base_class_name);
  91. Ref<GDScript> script;
  92. script.instance();
  93. script->set_source_code(_template);
  94. return script;
  95. }
  96. bool GDScriptLanguage::is_using_templates() {
  97. return true;
  98. }
  99. void GDScriptLanguage::make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script) {
  100. String _template = _get_processed_template(p_script->get_source_code(), p_base_class_name);
  101. p_script->set_source_code(_template);
  102. }
  103. static void get_function_names_recursively(const GDScriptParser::ClassNode *p_class, const String &p_prefix, Map<int, String> &r_funcs) {
  104. for (int i = 0; i < p_class->members.size(); i++) {
  105. if (p_class->members[i].type == GDScriptParser::ClassNode::Member::FUNCTION) {
  106. const GDScriptParser::FunctionNode *function = p_class->members[i].function;
  107. r_funcs[function->start_line] = p_prefix.empty() ? String(function->identifier->name) : p_prefix + "." + String(function->identifier->name);
  108. } else if (p_class->members[i].type == GDScriptParser::ClassNode::Member::CLASS) {
  109. String new_prefix = p_class->members[i].m_class->identifier->name;
  110. get_function_names_recursively(p_class->members[i].m_class, p_prefix.empty() ? new_prefix : p_prefix + "." + new_prefix, r_funcs);
  111. }
  112. }
  113. }
  114. bool GDScriptLanguage::validate(const String &p_script, int &r_line_error, int &r_col_error, String &r_test_error, const String &p_path, List<String> *r_functions, List<ScriptLanguage::Warning> *r_warnings, Set<int> *r_safe_lines) const {
  115. GDScriptParser parser;
  116. Error err = parser.parse(p_script, p_path, false);
  117. #ifdef DEBUG_ENABLED
  118. // FIXME: Warnings.
  119. // if (r_warnings) {
  120. // for (const List<GDScriptWarning>::Element *E = parser.get_warnings().front(); E; E = E->next()) {
  121. // const GDScriptWarning &warn = E->get();
  122. // ScriptLanguage::Warning w;
  123. // w.line = warn.line;
  124. // w.code = (int)warn.code;
  125. // w.string_code = GDScriptWarning::get_name_from_code(warn.code);
  126. // w.message = warn.get_message();
  127. // r_warnings->push_back(w);
  128. // }
  129. // }
  130. #endif
  131. if (err) {
  132. GDScriptParser::ParserError parse_error = parser.get_errors().front()->get();
  133. r_line_error = parse_error.line;
  134. r_col_error = parse_error.column;
  135. r_test_error = parse_error.message;
  136. return false;
  137. } else {
  138. const GDScriptParser::ClassNode *cl = parser.get_tree();
  139. Map<int, String> funcs;
  140. get_function_names_recursively(cl, "", funcs);
  141. for (Map<int, String>::Element *E = funcs.front(); E; E = E->next()) {
  142. r_functions->push_back(E->get() + ":" + itos(E->key()));
  143. }
  144. }
  145. return true;
  146. }
  147. bool GDScriptLanguage::has_named_classes() const {
  148. return false;
  149. }
  150. bool GDScriptLanguage::supports_builtin_mode() const {
  151. return true;
  152. }
  153. int GDScriptLanguage::find_function(const String &p_function, const String &p_code) const {
  154. GDScriptTokenizer tokenizer;
  155. tokenizer.set_source_code(p_code);
  156. int indent = 0;
  157. GDScriptTokenizer::Token current = tokenizer.scan();
  158. while (current.type != GDScriptTokenizer::Token::TK_EOF && current.type != GDScriptTokenizer::Token::ERROR) {
  159. if (current.type == GDScriptTokenizer::Token::INDENT) {
  160. indent++;
  161. } else if (current.type == GDScriptTokenizer::Token::DEDENT) {
  162. indent--;
  163. }
  164. if (indent == 0 && current.type == GDScriptTokenizer::Token::FUNC) {
  165. current = tokenizer.scan();
  166. if (current.is_identifier()) {
  167. String identifier = current.get_identifier();
  168. if (identifier == p_function) {
  169. return current.start_line;
  170. }
  171. }
  172. }
  173. current = tokenizer.scan();
  174. }
  175. return -1;
  176. }
  177. Script *GDScriptLanguage::create_script() const {
  178. return memnew(GDScript);
  179. }
  180. /* DEBUGGER FUNCTIONS */
  181. bool GDScriptLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
  182. //break because of parse error
  183. if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
  184. _debug_parse_err_line = p_line;
  185. _debug_parse_err_file = p_file;
  186. _debug_error = p_error;
  187. EngineDebugger::get_script_debugger()->debug(this, false, true);
  188. return true;
  189. } else {
  190. return false;
  191. }
  192. }
  193. bool GDScriptLanguage::debug_break(const String &p_error, bool p_allow_continue) {
  194. if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
  195. _debug_parse_err_line = -1;
  196. _debug_parse_err_file = "";
  197. _debug_error = p_error;
  198. bool is_error_breakpoint = p_error != "Breakpoint";
  199. EngineDebugger::get_script_debugger()->debug(this, p_allow_continue, is_error_breakpoint);
  200. return true;
  201. } else {
  202. return false;
  203. }
  204. }
  205. String GDScriptLanguage::debug_get_error() const {
  206. return _debug_error;
  207. }
  208. int GDScriptLanguage::debug_get_stack_level_count() const {
  209. if (_debug_parse_err_line >= 0) {
  210. return 1;
  211. }
  212. return _debug_call_stack_pos;
  213. }
  214. int GDScriptLanguage::debug_get_stack_level_line(int p_level) const {
  215. if (_debug_parse_err_line >= 0) {
  216. return _debug_parse_err_line;
  217. }
  218. ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, -1);
  219. int l = _debug_call_stack_pos - p_level - 1;
  220. return *(_call_stack[l].line);
  221. }
  222. String GDScriptLanguage::debug_get_stack_level_function(int p_level) const {
  223. if (_debug_parse_err_line >= 0) {
  224. return "";
  225. }
  226. ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, "");
  227. int l = _debug_call_stack_pos - p_level - 1;
  228. return _call_stack[l].function->get_name();
  229. }
  230. String GDScriptLanguage::debug_get_stack_level_source(int p_level) const {
  231. if (_debug_parse_err_line >= 0) {
  232. return _debug_parse_err_file;
  233. }
  234. ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, "");
  235. int l = _debug_call_stack_pos - p_level - 1;
  236. return _call_stack[l].function->get_source();
  237. }
  238. void GDScriptLanguage::debug_get_stack_level_locals(int p_level, List<String> *p_locals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
  239. if (_debug_parse_err_line >= 0) {
  240. return;
  241. }
  242. ERR_FAIL_INDEX(p_level, _debug_call_stack_pos);
  243. int l = _debug_call_stack_pos - p_level - 1;
  244. GDScriptFunction *f = _call_stack[l].function;
  245. List<Pair<StringName, int>> locals;
  246. f->debug_get_stack_member_state(*_call_stack[l].line, &locals);
  247. for (List<Pair<StringName, int>>::Element *E = locals.front(); E; E = E->next()) {
  248. p_locals->push_back(E->get().first);
  249. p_values->push_back(_call_stack[l].stack[E->get().second]);
  250. }
  251. }
  252. void GDScriptLanguage::debug_get_stack_level_members(int p_level, List<String> *p_members, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
  253. if (_debug_parse_err_line >= 0) {
  254. return;
  255. }
  256. ERR_FAIL_INDEX(p_level, _debug_call_stack_pos);
  257. int l = _debug_call_stack_pos - p_level - 1;
  258. GDScriptInstance *instance = _call_stack[l].instance;
  259. if (!instance) {
  260. return;
  261. }
  262. Ref<GDScript> script = instance->get_script();
  263. ERR_FAIL_COND(script.is_null());
  264. const Map<StringName, GDScript::MemberInfo> &mi = script->debug_get_member_indices();
  265. for (const Map<StringName, GDScript::MemberInfo>::Element *E = mi.front(); E; E = E->next()) {
  266. p_members->push_back(E->key());
  267. p_values->push_back(instance->debug_get_member_by_index(E->get().index));
  268. }
  269. }
  270. ScriptInstance *GDScriptLanguage::debug_get_stack_level_instance(int p_level) {
  271. if (_debug_parse_err_line >= 0) {
  272. return nullptr;
  273. }
  274. ERR_FAIL_INDEX_V(p_level, _debug_call_stack_pos, nullptr);
  275. int l = _debug_call_stack_pos - p_level - 1;
  276. ScriptInstance *instance = _call_stack[l].instance;
  277. return instance;
  278. }
  279. void GDScriptLanguage::debug_get_globals(List<String> *p_globals, List<Variant> *p_values, int p_max_subitems, int p_max_depth) {
  280. const Map<StringName, int> &name_idx = GDScriptLanguage::get_singleton()->get_global_map();
  281. const Variant *globals = GDScriptLanguage::get_singleton()->get_global_array();
  282. List<Pair<String, Variant>> cinfo;
  283. get_public_constants(&cinfo);
  284. for (const Map<StringName, int>::Element *E = name_idx.front(); E; E = E->next()) {
  285. if (ClassDB::class_exists(E->key()) || Engine::get_singleton()->has_singleton(E->key())) {
  286. continue;
  287. }
  288. bool is_script_constant = false;
  289. for (List<Pair<String, Variant>>::Element *CE = cinfo.front(); CE; CE = CE->next()) {
  290. if (CE->get().first == E->key()) {
  291. is_script_constant = true;
  292. break;
  293. }
  294. }
  295. if (is_script_constant) {
  296. continue;
  297. }
  298. const Variant &var = globals[E->value()];
  299. if (Object *obj = var) {
  300. if (Object::cast_to<GDScriptNativeClass>(obj)) {
  301. continue;
  302. }
  303. }
  304. bool skip = false;
  305. for (int i = 0; i < GlobalConstants::get_global_constant_count(); i++) {
  306. if (E->key() == GlobalConstants::get_global_constant_name(i)) {
  307. skip = true;
  308. break;
  309. }
  310. }
  311. if (skip) {
  312. continue;
  313. }
  314. p_globals->push_back(E->key());
  315. p_values->push_back(var);
  316. }
  317. }
  318. String GDScriptLanguage::debug_parse_stack_level_expression(int p_level, const String &p_expression, int p_max_subitems, int p_max_depth) {
  319. return "";
  320. }
  321. void GDScriptLanguage::get_recognized_extensions(List<String> *p_extensions) const {
  322. p_extensions->push_back("gd");
  323. }
  324. void GDScriptLanguage::get_public_functions(List<MethodInfo> *p_functions) const {
  325. for (int i = 0; i < GDScriptFunctions::FUNC_MAX; i++) {
  326. p_functions->push_back(GDScriptFunctions::get_info(GDScriptFunctions::Function(i)));
  327. }
  328. //not really "functions", but..
  329. {
  330. MethodInfo mi;
  331. mi.name = "preload";
  332. mi.arguments.push_back(PropertyInfo(Variant::STRING, "path"));
  333. mi.return_val = PropertyInfo(Variant::OBJECT, "", PROPERTY_HINT_RESOURCE_TYPE, "Resource");
  334. p_functions->push_back(mi);
  335. }
  336. {
  337. MethodInfo mi;
  338. mi.name = "assert";
  339. mi.return_val.type = Variant::NIL;
  340. mi.arguments.push_back(PropertyInfo(Variant::BOOL, "condition"));
  341. mi.arguments.push_back(PropertyInfo(Variant::STRING, "message"));
  342. mi.default_arguments.push_back(String());
  343. p_functions->push_back(mi);
  344. }
  345. }
  346. void GDScriptLanguage::get_public_constants(List<Pair<String, Variant>> *p_constants) const {
  347. Pair<String, Variant> pi;
  348. pi.first = "PI";
  349. pi.second = Math_PI;
  350. p_constants->push_back(pi);
  351. Pair<String, Variant> tau;
  352. tau.first = "TAU";
  353. tau.second = Math_TAU;
  354. p_constants->push_back(tau);
  355. Pair<String, Variant> infinity;
  356. infinity.first = "INF";
  357. infinity.second = Math_INF;
  358. p_constants->push_back(infinity);
  359. Pair<String, Variant> nan;
  360. nan.first = "NAN";
  361. nan.second = Math_NAN;
  362. p_constants->push_back(nan);
  363. }
  364. String GDScriptLanguage::make_function(const String &p_class, const String &p_name, const PackedStringArray &p_args) const {
  365. #ifdef TOOLS_ENABLED
  366. bool th = EditorSettings::get_singleton()->get_setting("text_editor/completion/add_type_hints");
  367. #else
  368. bool th = false;
  369. #endif
  370. String s = "func " + p_name + "(";
  371. if (p_args.size()) {
  372. for (int i = 0; i < p_args.size(); i++) {
  373. if (i > 0) {
  374. s += ", ";
  375. }
  376. s += p_args[i].get_slice(":", 0);
  377. if (th) {
  378. String type = p_args[i].get_slice(":", 1);
  379. if (!type.empty() && type != "var") {
  380. s += ": " + type;
  381. }
  382. }
  383. }
  384. }
  385. s += String(")") + (th ? " -> void" : "") + ":\n" + _get_indentation() + "pass # Replace with function body.\n";
  386. return s;
  387. }
  388. //////// COMPLETION //////////
  389. // FIXME: Readd completion
  390. Error GDScriptLanguage::complete_code(const String &p_code, const String &p_path, Object *p_owner, List<ScriptCodeCompletionOption> *r_options, bool &r_forced, String &r_call_hint) {
  391. return OK;
  392. }
  393. //////// END COMPLETION //////////
  394. String GDScriptLanguage::_get_indentation() const {
  395. #ifdef TOOLS_ENABLED
  396. if (Engine::get_singleton()->is_editor_hint()) {
  397. bool use_space_indentation = EDITOR_DEF("text_editor/indent/type", false);
  398. if (use_space_indentation) {
  399. int indent_size = EDITOR_DEF("text_editor/indent/size", 4);
  400. String space_indent = "";
  401. for (int i = 0; i < indent_size; i++) {
  402. space_indent += " ";
  403. }
  404. return space_indent;
  405. }
  406. }
  407. #endif
  408. return "\t";
  409. }
  410. void GDScriptLanguage::auto_indent_code(String &p_code, int p_from_line, int p_to_line) const {
  411. String indent = _get_indentation();
  412. Vector<String> lines = p_code.split("\n");
  413. List<int> indent_stack;
  414. for (int i = 0; i < lines.size(); i++) {
  415. String l = lines[i];
  416. int tc = 0;
  417. for (int j = 0; j < l.length(); j++) {
  418. if (l[j] == ' ' || l[j] == '\t') {
  419. tc++;
  420. } else {
  421. break;
  422. }
  423. }
  424. String st = l.substr(tc, l.length()).strip_edges();
  425. if (st == "" || st.begins_with("#")) {
  426. continue; //ignore!
  427. }
  428. int ilevel = 0;
  429. if (indent_stack.size()) {
  430. ilevel = indent_stack.back()->get();
  431. }
  432. if (tc > ilevel) {
  433. indent_stack.push_back(tc);
  434. } else if (tc < ilevel) {
  435. while (indent_stack.size() && indent_stack.back()->get() > tc) {
  436. indent_stack.pop_back();
  437. }
  438. if (indent_stack.size() && indent_stack.back()->get() != tc) {
  439. indent_stack.push_back(tc); //this is not right but gets the job done
  440. }
  441. }
  442. if (i >= p_from_line) {
  443. l = "";
  444. for (int j = 0; j < indent_stack.size(); j++) {
  445. l += indent;
  446. }
  447. l += st;
  448. } else if (i > p_to_line) {
  449. break;
  450. }
  451. lines.write[i] = l;
  452. }
  453. p_code = "";
  454. for (int i = 0; i < lines.size(); i++) {
  455. if (i > 0) {
  456. p_code += "\n";
  457. }
  458. p_code += lines[i];
  459. }
  460. }
  461. #ifdef TOOLS_ENABLED
  462. Error GDScriptLanguage::lookup_code(const String &p_code, const String &p_symbol, const String &p_path, Object *p_owner, LookupResult &r_result) {
  463. // FIXME: Implement lookup.
  464. return ERR_CANT_RESOLVE;
  465. }
  466. #endif