gdscript_editor.cpp 18 KB

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