test_gdscript.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. /*************************************************************************/
  2. /* test_gdscript.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2021 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2021 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 "test_gdscript.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/file_access_pack.h"
  33. #include "core/os/file_access.h"
  34. #include "core/os/main_loop.h"
  35. #include "core/os/os.h"
  36. #include "core/string/string_builder.h"
  37. #include "scene/resources/packed_scene.h"
  38. #include "modules/gdscript/gdscript_analyzer.h"
  39. #include "modules/gdscript/gdscript_compiler.h"
  40. #include "modules/gdscript/gdscript_parser.h"
  41. #include "modules/gdscript/gdscript_tokenizer.h"
  42. #ifdef TOOLS_ENABLED
  43. #include "editor/editor_settings.h"
  44. #endif
  45. namespace TestGDScript {
  46. static void test_tokenizer(const String &p_code, const Vector<String> &p_lines) {
  47. GDScriptTokenizer tokenizer;
  48. tokenizer.set_source_code(p_code);
  49. int tab_size = 4;
  50. #ifdef TOOLS_ENABLED
  51. if (EditorSettings::get_singleton()) {
  52. tab_size = EditorSettings::get_singleton()->get_setting("text_editor/indent/size");
  53. }
  54. #endif // TOOLS_ENABLED
  55. String tab = String(" ").repeat(tab_size);
  56. GDScriptTokenizer::Token current = tokenizer.scan();
  57. while (current.type != GDScriptTokenizer::Token::TK_EOF) {
  58. StringBuilder token;
  59. token += " --> "; // Padding for line number.
  60. for (int l = current.start_line; l <= current.end_line; l++) {
  61. print_line(vformat("%04d %s", l, p_lines[l - 1]).replace("\t", tab));
  62. }
  63. {
  64. // Print carets to point at the token.
  65. StringBuilder pointer;
  66. pointer += " "; // Padding for line number.
  67. int rightmost_column = current.rightmost_column;
  68. if (current.end_line > current.start_line) {
  69. rightmost_column--; // Don't point to the newline as a column.
  70. }
  71. for (int col = 1; col < rightmost_column; col++) {
  72. if (col < current.leftmost_column) {
  73. pointer += " ";
  74. } else {
  75. pointer += "^";
  76. }
  77. }
  78. print_line(pointer.as_string());
  79. }
  80. token += current.get_name();
  81. if (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::LITERAL || current.type == GDScriptTokenizer::Token::IDENTIFIER || current.type == GDScriptTokenizer::Token::ANNOTATION) {
  82. token += "(";
  83. token += Variant::get_type_name(current.literal.get_type());
  84. token += ") ";
  85. token += current.literal;
  86. }
  87. print_line(token.as_string());
  88. print_line("-------------------------------------------------------");
  89. current = tokenizer.scan();
  90. }
  91. print_line(current.get_name()); // Should be EOF
  92. }
  93. static void test_parser(const String &p_code, const String &p_script_path, const Vector<String> &p_lines) {
  94. GDScriptParser parser;
  95. Error err = parser.parse(p_code, p_script_path, false);
  96. if (err != OK) {
  97. const List<GDScriptParser::ParserError> &errors = parser.get_errors();
  98. for (const List<GDScriptParser::ParserError>::Element *E = errors.front(); E != nullptr; E = E->next()) {
  99. const GDScriptParser::ParserError &error = E->get();
  100. print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message));
  101. }
  102. }
  103. #ifdef TOOLS_ENABLED
  104. GDScriptParser::TreePrinter printer;
  105. printer.print_tree(parser);
  106. #endif
  107. }
  108. static void test_compiler(const String &p_code, const String &p_script_path, const Vector<String> &p_lines) {
  109. GDScriptParser parser;
  110. Error err = parser.parse(p_code, p_script_path, false);
  111. if (err != OK) {
  112. print_line("Error in parser:");
  113. const List<GDScriptParser::ParserError> &errors = parser.get_errors();
  114. for (const List<GDScriptParser::ParserError>::Element *E = errors.front(); E != nullptr; E = E->next()) {
  115. const GDScriptParser::ParserError &error = E->get();
  116. print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message));
  117. }
  118. return;
  119. }
  120. GDScriptAnalyzer analyzer(&parser);
  121. err = analyzer.analyze();
  122. if (err != OK) {
  123. print_line("Error in analyzer:");
  124. const List<GDScriptParser::ParserError> &errors = parser.get_errors();
  125. for (const List<GDScriptParser::ParserError>::Element *E = errors.front(); E != nullptr; E = E->next()) {
  126. const GDScriptParser::ParserError &error = E->get();
  127. print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message));
  128. }
  129. return;
  130. }
  131. GDScriptCompiler compiler;
  132. Ref<GDScript> script;
  133. script.instance();
  134. script->set_path(p_script_path);
  135. err = compiler.compile(&parser, script.ptr(), false);
  136. if (err) {
  137. print_line("Error in compiler:");
  138. print_line(vformat("%02d:%02d: %s", compiler.get_error_line(), compiler.get_error_column(), compiler.get_error()));
  139. return;
  140. }
  141. for (const Map<StringName, GDScriptFunction *>::Element *E = script->get_member_functions().front(); E; E = E->next()) {
  142. const GDScriptFunction *func = E->value();
  143. String signature = "Disassembling " + func->get_name().operator String() + "(";
  144. for (int i = 0; i < func->get_argument_count(); i++) {
  145. if (i > 0) {
  146. signature += ", ";
  147. }
  148. signature += func->get_argument_name(i);
  149. }
  150. print_line(signature + ")");
  151. #ifdef TOOLS_ENABLED
  152. func->disassemble(p_lines);
  153. #endif
  154. print_line("");
  155. print_line("");
  156. }
  157. }
  158. void init_autoloads() {
  159. Map<StringName, ProjectSettings::AutoloadInfo> autoloads = ProjectSettings::get_singleton()->get_autoload_list();
  160. // First pass, add the constants so they exist before any script is loaded.
  161. for (Map<StringName, ProjectSettings::AutoloadInfo>::Element *E = autoloads.front(); E; E = E->next()) {
  162. const ProjectSettings::AutoloadInfo &info = E->get();
  163. if (info.is_singleton) {
  164. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  165. ScriptServer::get_language(i)->add_global_constant(info.name, Variant());
  166. }
  167. }
  168. }
  169. // Second pass, load into global constants.
  170. for (Map<StringName, ProjectSettings::AutoloadInfo>::Element *E = autoloads.front(); E; E = E->next()) {
  171. const ProjectSettings::AutoloadInfo &info = E->get();
  172. if (!info.is_singleton) {
  173. // Skip non-singletons since we don't have a scene tree here anyway.
  174. continue;
  175. }
  176. RES res = ResourceLoader::load(info.path);
  177. ERR_CONTINUE_MSG(res.is_null(), "Can't autoload: " + info.path);
  178. Node *n = nullptr;
  179. if (res->is_class("PackedScene")) {
  180. Ref<PackedScene> ps = res;
  181. n = ps->instance();
  182. } else if (res->is_class("Script")) {
  183. Ref<Script> script_res = res;
  184. StringName ibt = script_res->get_instance_base_type();
  185. bool valid_type = ClassDB::is_parent_class(ibt, "Node");
  186. ERR_CONTINUE_MSG(!valid_type, "Script does not inherit a Node: " + info.path);
  187. Object *obj = ClassDB::instance(ibt);
  188. ERR_CONTINUE_MSG(obj == nullptr,
  189. "Cannot instance script for autoload, expected 'Node' inheritance, got: " +
  190. String(ibt));
  191. n = Object::cast_to<Node>(obj);
  192. n->set_script(script_res);
  193. }
  194. ERR_CONTINUE_MSG(!n, "Path in autoload not a node or script: " + info.path);
  195. n->set_name(info.name);
  196. for (int i = 0; i < ScriptServer::get_language_count(); i++) {
  197. ScriptServer::get_language(i)->add_global_constant(info.name, n);
  198. }
  199. }
  200. }
  201. void test(TestType p_type) {
  202. List<String> cmdlargs = OS::get_singleton()->get_cmdline_args();
  203. if (cmdlargs.is_empty()) {
  204. return;
  205. }
  206. String test = cmdlargs.back()->get();
  207. if (!test.ends_with(".gd")) {
  208. print_line("This test expects a path to a GDScript file as its last parameter. Got: " + test);
  209. return;
  210. }
  211. FileAccessRef fa = FileAccess::open(test, FileAccess::READ);
  212. ERR_FAIL_COND_MSG(!fa, "Could not open file: " + test);
  213. // Init PackedData since it's used by ProjectSettings.
  214. PackedData *packed_data = memnew(PackedData);
  215. // Setup project settings since it's needed by the languages to get the global scripts.
  216. // This also sets up the base resource path.
  217. Error err = ProjectSettings::get_singleton()->setup(fa->get_path_absolute().get_base_dir(), String(), true);
  218. if (err) {
  219. print_line("Could not load project settings.");
  220. // Keep going since some scripts still work without this.
  221. }
  222. // Initialize the language for the test routine.
  223. ScriptServer::init_languages();
  224. init_autoloads();
  225. Vector<uint8_t> buf;
  226. int flen = fa->get_len();
  227. buf.resize(fa->get_len() + 1);
  228. fa->get_buffer(buf.ptrw(), flen);
  229. buf.write[flen] = 0;
  230. String code;
  231. code.parse_utf8((const char *)&buf[0]);
  232. Vector<String> lines;
  233. int last = 0;
  234. for (int i = 0; i <= code.length(); i++) {
  235. if (code[i] == '\n' || code[i] == 0) {
  236. lines.push_back(code.substr(last, i - last));
  237. last = i + 1;
  238. }
  239. }
  240. switch (p_type) {
  241. case TEST_TOKENIZER:
  242. test_tokenizer(code, lines);
  243. break;
  244. case TEST_PARSER:
  245. test_parser(code, test, lines);
  246. break;
  247. case TEST_COMPILER:
  248. test_compiler(code, test, lines);
  249. break;
  250. case TEST_BYTECODE:
  251. print_line("Not implemented.");
  252. }
  253. // Destroy stuff we set up earlier.
  254. ScriptServer::finish_languages();
  255. memdelete(packed_data);
  256. }
  257. } // namespace TestGDScript