test_gdscript.cpp 12 KB

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