test_gdscript.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. /**************************************************************************/
  2. /* test_gdscript.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 "test_gdscript.h"
  31. #include "../gdscript_analyzer.h"
  32. #include "../gdscript_compiler.h"
  33. #include "../gdscript_parser.h"
  34. #include "../gdscript_tokenizer.h"
  35. #include "../gdscript_tokenizer_buffer.h"
  36. #include "core/config/project_settings.h"
  37. #include "core/io/file_access.h"
  38. #include "core/os/os.h"
  39. #include "core/string/string_builder.h"
  40. #ifdef TOOLS_ENABLED
  41. #include "editor/editor_settings.h"
  42. #endif
  43. namespace GDScriptTests {
  44. static void test_tokenizer(const String &p_code, const Vector<String> &p_lines) {
  45. GDScriptTokenizerText tokenizer;
  46. tokenizer.set_source_code(p_code);
  47. int tab_size = 4;
  48. #ifdef TOOLS_ENABLED
  49. if (EditorSettings::get_singleton()) {
  50. tab_size = EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");
  51. }
  52. #endif // TOOLS_ENABLED
  53. String tab = String(" ").repeat(tab_size);
  54. GDScriptTokenizer::Token current = tokenizer.scan();
  55. while (current.type != GDScriptTokenizer::Token::TK_EOF) {
  56. StringBuilder token;
  57. token += " --> "; // Padding for line number.
  58. for (int l = current.start_line; l <= current.end_line && l <= p_lines.size(); l++) {
  59. print_line(vformat("%04d %s", l, p_lines[l - 1]).replace("\t", tab));
  60. }
  61. {
  62. // Print carets to point at the token.
  63. StringBuilder pointer;
  64. pointer += " "; // Padding for line number.
  65. int rightmost_column = current.rightmost_column;
  66. if (current.end_line > current.start_line) {
  67. rightmost_column--; // Don't point to the newline as a column.
  68. }
  69. for (int col = 1; col < rightmost_column; col++) {
  70. if (col < current.leftmost_column) {
  71. pointer += " ";
  72. } else {
  73. pointer += "^";
  74. }
  75. }
  76. print_line(pointer.as_string());
  77. }
  78. token += current.get_name();
  79. if (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::LITERAL || current.type == GDScriptTokenizer::Token::IDENTIFIER || current.type == GDScriptTokenizer::Token::ANNOTATION) {
  80. token += "(";
  81. token += Variant::get_type_name(current.literal.get_type());
  82. token += ") ";
  83. token += current.literal;
  84. }
  85. print_line(token.as_string());
  86. print_line("-------------------------------------------------------");
  87. current = tokenizer.scan();
  88. }
  89. print_line(current.get_name()); // Should be EOF
  90. }
  91. static void test_tokenizer_buffer(const Vector<uint8_t> &p_buffer, const Vector<String> &p_lines);
  92. static void test_tokenizer_buffer(const String &p_code, const Vector<String> &p_lines) {
  93. Vector<uint8_t> binary = GDScriptTokenizerBuffer::parse_code_string(p_code, GDScriptTokenizerBuffer::COMPRESS_NONE);
  94. test_tokenizer_buffer(binary, p_lines);
  95. }
  96. static void test_tokenizer_buffer(const Vector<uint8_t> &p_buffer, const Vector<String> &p_lines) {
  97. GDScriptTokenizerBuffer tokenizer;
  98. tokenizer.set_code_buffer(p_buffer);
  99. int tab_size = 4;
  100. #ifdef TOOLS_ENABLED
  101. if (EditorSettings::get_singleton()) {
  102. tab_size = EditorSettings::get_singleton()->get_setting("text_editor/behavior/indent/size");
  103. }
  104. #endif // TOOLS_ENABLED
  105. String tab = String(" ").repeat(tab_size);
  106. GDScriptTokenizer::Token current = tokenizer.scan();
  107. while (current.type != GDScriptTokenizer::Token::TK_EOF) {
  108. StringBuilder token;
  109. token += " --> "; // Padding for line number.
  110. for (int l = current.start_line; l <= current.end_line && l <= p_lines.size(); l++) {
  111. print_line(vformat("%04d %s", l, p_lines[l - 1]).replace("\t", tab));
  112. }
  113. token += current.get_name();
  114. if (current.type == GDScriptTokenizer::Token::ERROR || current.type == GDScriptTokenizer::Token::LITERAL || current.type == GDScriptTokenizer::Token::IDENTIFIER || current.type == GDScriptTokenizer::Token::ANNOTATION) {
  115. token += "(";
  116. token += Variant::get_type_name(current.literal.get_type());
  117. token += ") ";
  118. token += current.literal;
  119. }
  120. print_line(token.as_string());
  121. print_line("-------------------------------------------------------");
  122. current = tokenizer.scan();
  123. }
  124. print_line(current.get_name()); // Should be EOF
  125. }
  126. static void test_parser(const String &p_code, const String &p_script_path, const Vector<String> &p_lines) {
  127. GDScriptParser parser;
  128. Error err = parser.parse(p_code, p_script_path, false);
  129. if (err != OK) {
  130. const List<GDScriptParser::ParserError> &errors = parser.get_errors();
  131. for (const GDScriptParser::ParserError &error : errors) {
  132. print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message));
  133. }
  134. }
  135. GDScriptAnalyzer analyzer(&parser);
  136. err = analyzer.analyze();
  137. if (err != OK) {
  138. const List<GDScriptParser::ParserError> &errors = parser.get_errors();
  139. for (const GDScriptParser::ParserError &error : errors) {
  140. print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message));
  141. }
  142. }
  143. #ifdef TOOLS_ENABLED
  144. GDScriptParser::TreePrinter printer;
  145. printer.print_tree(parser);
  146. #endif
  147. }
  148. static void disassemble_function(const GDScriptFunction *p_func, const Vector<String> &p_lines) {
  149. ERR_FAIL_NULL(p_func);
  150. String arg_string;
  151. bool is_first_arg = true;
  152. for (const PropertyInfo &arg_info : p_func->get_method_info().arguments) {
  153. if (!is_first_arg) {
  154. arg_string += ", ";
  155. }
  156. arg_string += arg_info.name;
  157. is_first_arg = false;
  158. }
  159. print_line(vformat("Function %s(%s)", p_func->get_name(), arg_string));
  160. #ifdef TOOLS_ENABLED
  161. p_func->disassemble(p_lines);
  162. #endif
  163. print_line("");
  164. print_line("");
  165. }
  166. static void recursively_disassemble_functions(const Ref<GDScript> p_script, const Vector<String> &p_lines) {
  167. print_line(vformat("Class %s", p_script->get_fully_qualified_name()));
  168. print_line("");
  169. print_line("");
  170. const GDScriptFunction *implicit_initializer = p_script->get_implicit_initializer();
  171. if (implicit_initializer != nullptr) {
  172. disassemble_function(implicit_initializer, p_lines);
  173. }
  174. const GDScriptFunction *implicit_ready = p_script->get_implicit_ready();
  175. if (implicit_ready != nullptr) {
  176. disassemble_function(implicit_ready, p_lines);
  177. }
  178. const GDScriptFunction *static_initializer = p_script->get_static_initializer();
  179. if (static_initializer != nullptr) {
  180. disassemble_function(static_initializer, p_lines);
  181. }
  182. for (const KeyValue<GDScriptFunction *, GDScript::LambdaInfo> &E : p_script->get_lambda_info()) {
  183. disassemble_function(E.key, p_lines);
  184. }
  185. for (const KeyValue<StringName, GDScriptFunction *> &E : p_script->get_member_functions()) {
  186. disassemble_function(E.value, p_lines);
  187. }
  188. for (const KeyValue<StringName, Ref<GDScript>> &E : p_script->get_subclasses()) {
  189. recursively_disassemble_functions(E.value, p_lines);
  190. }
  191. }
  192. static void test_compiler(const String &p_code, const String &p_script_path, const Vector<String> &p_lines) {
  193. GDScriptParser parser;
  194. Error err = parser.parse(p_code, p_script_path, false);
  195. if (err != OK) {
  196. print_line("Error in parser:");
  197. const List<GDScriptParser::ParserError> &errors = parser.get_errors();
  198. for (const GDScriptParser::ParserError &error : errors) {
  199. print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message));
  200. }
  201. return;
  202. }
  203. GDScriptAnalyzer analyzer(&parser);
  204. err = analyzer.analyze();
  205. if (err != OK) {
  206. print_line("Error in analyzer:");
  207. const List<GDScriptParser::ParserError> &errors = parser.get_errors();
  208. for (const GDScriptParser::ParserError &error : errors) {
  209. print_line(vformat("%02d:%02d: %s", error.line, error.column, error.message));
  210. }
  211. return;
  212. }
  213. GDScriptCompiler compiler;
  214. Ref<GDScript> script;
  215. script.instantiate();
  216. script->set_path(p_script_path);
  217. err = compiler.compile(&parser, script.ptr(), false);
  218. if (err) {
  219. print_line("Error in compiler:");
  220. print_line(vformat("%02d:%02d: %s", compiler.get_error_line(), compiler.get_error_column(), compiler.get_error()));
  221. return;
  222. }
  223. recursively_disassemble_functions(script, p_lines);
  224. }
  225. void test(TestType p_type) {
  226. List<String> cmdlargs = OS::get_singleton()->get_cmdline_args();
  227. if (cmdlargs.is_empty()) {
  228. return;
  229. }
  230. String test = cmdlargs.back()->get();
  231. if (!test.ends_with(".gd") && !test.ends_with(".gdc")) {
  232. print_line("This test expects a path to a GDScript file as its last parameter. Got: " + test);
  233. return;
  234. }
  235. Ref<FileAccess> fa = FileAccess::open(test, FileAccess::READ);
  236. ERR_FAIL_COND_MSG(fa.is_null(), "Could not open file: " + test);
  237. // Initialize the language for the test routine.
  238. init_language(fa->get_path_absolute().get_base_dir());
  239. // Load global classes.
  240. TypedArray<Dictionary> script_classes = ProjectSettings::get_singleton()->get_global_class_list();
  241. for (int i = 0; i < script_classes.size(); i++) {
  242. Dictionary c = script_classes[i];
  243. if (!c.has("class") || !c.has("language") || !c.has("path") || !c.has("base")) {
  244. continue;
  245. }
  246. ScriptServer::add_global_class(c["class"], c["base"], c["language"], c["path"]);
  247. }
  248. Vector<uint8_t> buf;
  249. uint64_t flen = fa->get_length();
  250. buf.resize(flen + 1);
  251. fa->get_buffer(buf.ptrw(), flen);
  252. buf.write[flen] = 0;
  253. String code;
  254. code.parse_utf8((const char *)&buf[0]);
  255. Vector<String> lines;
  256. int last = 0;
  257. for (int i = 0; i <= code.length(); i++) {
  258. if (code[i] == '\n' || code[i] == 0) {
  259. lines.push_back(code.substr(last, i - last));
  260. last = i + 1;
  261. }
  262. }
  263. switch (p_type) {
  264. case TEST_TOKENIZER:
  265. test_tokenizer(code, lines);
  266. break;
  267. case TEST_TOKENIZER_BUFFER:
  268. if (test.ends_with(".gdc")) {
  269. test_tokenizer_buffer(buf, lines);
  270. } else {
  271. test_tokenizer_buffer(code, lines);
  272. }
  273. break;
  274. case TEST_PARSER:
  275. test_parser(code, test, lines);
  276. break;
  277. case TEST_COMPILER:
  278. test_compiler(code, test, lines);
  279. break;
  280. case TEST_BYTECODE:
  281. print_line("Not implemented.");
  282. }
  283. finish_language();
  284. }
  285. } // namespace GDScriptTests