gdscript_translation_parser_plugin.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /*************************************************************************/
  2. /* gdscript_translation_parser_plugin.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 "gdscript_translation_parser_plugin.h"
  31. #include "core/io/resource_loader.h"
  32. #include "modules/gdscript/gdscript.h"
  33. void GDScriptEditorTranslationParserPlugin::get_recognized_extensions(List<String> *r_extensions) const {
  34. GDScriptLanguage::get_singleton()->get_recognized_extensions(r_extensions);
  35. }
  36. Error GDScriptEditorTranslationParserPlugin::parse_file(const String &p_path, Vector<String> *r_ids, Vector<Vector<String>> *r_ids_ctx_plural) {
  37. // Extract all translatable strings using the parsed tree from GDSriptParser.
  38. // The strategy is to find all ExpressionNode and AssignmentNode from the tree and extract strings if relevant, i.e
  39. // Search strings in ExpressionNode -> CallNode -> tr(), set_text(), set_placeholder() etc.
  40. // Search strings in AssignmentNode -> text = "__", hint_tooltip = "__" etc.
  41. Error err;
  42. RES loaded_res = ResourceLoader::load(p_path, "", ResourceFormatLoader::CACHE_MODE_REUSE, &err);
  43. if (err) {
  44. ERR_PRINT("Failed to load " + p_path);
  45. return err;
  46. }
  47. ids = r_ids;
  48. ids_ctx_plural = r_ids_ctx_plural;
  49. Ref<GDScript> gdscript = loaded_res;
  50. String source_code = gdscript->get_source_code();
  51. GDScriptParser parser;
  52. err = parser.parse(source_code, p_path, false);
  53. if (err != OK) {
  54. ERR_PRINT("Failed to parse with GDScript with GDScriptParser.");
  55. return err;
  56. }
  57. // Traverse through the parsed tree from GDScriptParser.
  58. GDScriptParser::ClassNode *c = parser.get_tree();
  59. _traverse_class(c);
  60. return OK;
  61. }
  62. void GDScriptEditorTranslationParserPlugin::_traverse_class(const GDScriptParser::ClassNode *p_class) {
  63. for (int i = 0; i < p_class->members.size(); i++) {
  64. const GDScriptParser::ClassNode::Member &m = p_class->members[i];
  65. // There are 7 types of Member, but only class, function and variable can contain translatable strings.
  66. switch (m.type) {
  67. case GDScriptParser::ClassNode::Member::CLASS:
  68. _traverse_class(m.m_class);
  69. break;
  70. case GDScriptParser::ClassNode::Member::FUNCTION:
  71. _traverse_function(m.function);
  72. break;
  73. case GDScriptParser::ClassNode::Member::VARIABLE:
  74. _read_variable(m.variable);
  75. break;
  76. default:
  77. break;
  78. }
  79. }
  80. }
  81. void GDScriptEditorTranslationParserPlugin::_traverse_function(const GDScriptParser::FunctionNode *p_func) {
  82. _traverse_block(p_func->body);
  83. }
  84. void GDScriptEditorTranslationParserPlugin::_read_variable(const GDScriptParser::VariableNode *p_var) {
  85. _assess_expression(p_var->initializer);
  86. }
  87. void GDScriptEditorTranslationParserPlugin::_traverse_block(const GDScriptParser::SuiteNode *p_suite) {
  88. if (!p_suite) {
  89. return;
  90. }
  91. const Vector<GDScriptParser::Node *> &statements = p_suite->statements;
  92. for (int i = 0; i < statements.size(); i++) {
  93. GDScriptParser::Node *statement = statements[i];
  94. // Statements with Node type constant, break, continue, pass, breakpoint are skipped because they can't contain translatable strings.
  95. switch (statement->type) {
  96. case GDScriptParser::Node::VARIABLE:
  97. _assess_expression(static_cast<GDScriptParser::VariableNode *>(statement)->initializer);
  98. break;
  99. case GDScriptParser::Node::IF: {
  100. GDScriptParser::IfNode *if_node = static_cast<GDScriptParser::IfNode *>(statement);
  101. _assess_expression(if_node->condition);
  102. //FIXME : if the elif logic is changed in GDScriptParser, then this probably will have to change as well. See GDScriptParser::TreePrinter::print_if().
  103. _traverse_block(if_node->true_block);
  104. _traverse_block(if_node->false_block);
  105. break;
  106. }
  107. case GDScriptParser::Node::FOR: {
  108. GDScriptParser::ForNode *for_node = static_cast<GDScriptParser::ForNode *>(statement);
  109. _assess_expression(for_node->list);
  110. _traverse_block(for_node->loop);
  111. break;
  112. }
  113. case GDScriptParser::Node::WHILE: {
  114. GDScriptParser::WhileNode *while_node = static_cast<GDScriptParser::WhileNode *>(statement);
  115. _assess_expression(while_node->condition);
  116. _traverse_block(while_node->loop);
  117. break;
  118. }
  119. case GDScriptParser::Node::MATCH: {
  120. GDScriptParser::MatchNode *match_node = static_cast<GDScriptParser::MatchNode *>(statement);
  121. _assess_expression(match_node->test);
  122. for (int j = 0; j < match_node->branches.size(); j++) {
  123. _traverse_block(match_node->branches[j]->block);
  124. }
  125. break;
  126. }
  127. case GDScriptParser::Node::RETURN:
  128. _assess_expression(static_cast<GDScriptParser::ReturnNode *>(statement)->return_value);
  129. break;
  130. case GDScriptParser::Node::ASSERT:
  131. _assess_expression((static_cast<GDScriptParser::AssertNode *>(statement))->condition);
  132. break;
  133. case GDScriptParser::Node::ASSIGNMENT:
  134. _assess_assignment(static_cast<GDScriptParser::AssignmentNode *>(statement));
  135. break;
  136. default:
  137. if (statement->is_expression()) {
  138. _assess_expression(static_cast<GDScriptParser::ExpressionNode *>(statement));
  139. }
  140. break;
  141. }
  142. }
  143. }
  144. void GDScriptEditorTranslationParserPlugin::_assess_expression(GDScriptParser::ExpressionNode *p_expression) {
  145. // Explore all ExpressionNodes to find CallNodes which contain translation strings, such as tr(), set_text() etc.
  146. // tr() can be embedded quite deep within multiple ExpressionNodes so need to dig down to search through all ExpressionNodes.
  147. if (!p_expression) {
  148. return;
  149. }
  150. // ExpressionNode of type await, cast, get_node, identifier, literal, preload, self, subscript, unary are ignored as they can't be CallNode
  151. // containing translation strings.
  152. switch (p_expression->type) {
  153. case GDScriptParser::Node::ARRAY: {
  154. GDScriptParser::ArrayNode *array_node = static_cast<GDScriptParser::ArrayNode *>(p_expression);
  155. for (int i = 0; i < array_node->elements.size(); i++) {
  156. _assess_expression(array_node->elements[i]);
  157. }
  158. break;
  159. }
  160. case GDScriptParser::Node::ASSIGNMENT:
  161. _assess_assignment(static_cast<GDScriptParser::AssignmentNode *>(p_expression));
  162. break;
  163. case GDScriptParser::Node::BINARY_OPERATOR: {
  164. GDScriptParser::BinaryOpNode *binary_op_node = static_cast<GDScriptParser::BinaryOpNode *>(p_expression);
  165. _assess_expression(binary_op_node->left_operand);
  166. _assess_expression(binary_op_node->right_operand);
  167. break;
  168. }
  169. case GDScriptParser::Node::CALL: {
  170. GDScriptParser::CallNode *call_node = static_cast<GDScriptParser::CallNode *>(p_expression);
  171. _extract_from_call(call_node);
  172. for (int i = 0; i < call_node->arguments.size(); i++) {
  173. _assess_expression(call_node->arguments[i]);
  174. }
  175. } break;
  176. case GDScriptParser::Node::DICTIONARY: {
  177. GDScriptParser::DictionaryNode *dict_node = static_cast<GDScriptParser::DictionaryNode *>(p_expression);
  178. for (int i = 0; i < dict_node->elements.size(); i++) {
  179. _assess_expression(dict_node->elements[i].key);
  180. _assess_expression(dict_node->elements[i].value);
  181. }
  182. break;
  183. }
  184. case GDScriptParser::Node::TERNARY_OPERATOR: {
  185. GDScriptParser::TernaryOpNode *ternary_op_node = static_cast<GDScriptParser::TernaryOpNode *>(p_expression);
  186. _assess_expression(ternary_op_node->condition);
  187. _assess_expression(ternary_op_node->true_expr);
  188. _assess_expression(ternary_op_node->false_expr);
  189. break;
  190. }
  191. default:
  192. break;
  193. }
  194. }
  195. void GDScriptEditorTranslationParserPlugin::_assess_assignment(GDScriptParser::AssignmentNode *p_assignment) {
  196. // Extract the translatable strings coming from assignments. For example, get_node("Label").text = "____"
  197. StringName assignee_name;
  198. if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {
  199. assignee_name = static_cast<GDScriptParser::IdentifierNode *>(p_assignment->assignee)->name;
  200. } else if (p_assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT) {
  201. assignee_name = static_cast<GDScriptParser::SubscriptNode *>(p_assignment->assignee)->attribute->name;
  202. }
  203. if (assignment_patterns.has(assignee_name) && p_assignment->assigned_value->type == GDScriptParser::Node::LITERAL) {
  204. // If the assignment is towards one of the extract patterns (text, hint_tooltip etc.), and the value is a string literal, we collect the string.
  205. ids->push_back(static_cast<GDScriptParser::LiteralNode *>(p_assignment->assigned_value)->value);
  206. } else if (assignee_name == fd_filters && p_assignment->assigned_value->type == GDScriptParser::Node::CALL) {
  207. // FileDialog.filters accepts assignment in the form of PackedStringArray. For example,
  208. // get_node("FileDialog").filters = PackedStringArray(["*.png ; PNG Images","*.gd ; GDScript Files"]).
  209. GDScriptParser::CallNode *call_node = static_cast<GDScriptParser::CallNode *>(p_assignment->assigned_value);
  210. if (call_node->arguments[0]->type == GDScriptParser::Node::ARRAY) {
  211. GDScriptParser::ArrayNode *array_node = static_cast<GDScriptParser::ArrayNode *>(call_node->arguments[0]);
  212. // Extract the name in "extension ; name" of PackedStringArray.
  213. for (int i = 0; i < array_node->elements.size(); i++) {
  214. _extract_fd_literals(array_node->elements[i]);
  215. }
  216. }
  217. } else {
  218. // If the assignee is not in extract patterns or the assigned_value is not Literal type, try to see if the assigned_value contains tr().
  219. _assess_expression(p_assignment->assigned_value);
  220. }
  221. }
  222. void GDScriptEditorTranslationParserPlugin::_extract_from_call(GDScriptParser::CallNode *p_call) {
  223. // Extract the translatable strings coming from function calls. For example:
  224. // tr("___"), get_node("Label").set_text("____"), get_node("LineEdit").set_placeholder("____").
  225. StringName function_name = p_call->function_name;
  226. // Variables for extracting tr() and tr_n().
  227. Vector<String> id_ctx_plural;
  228. id_ctx_plural.resize(3);
  229. bool extract_id_ctx_plural = true;
  230. if (function_name == tr_func) {
  231. // Extract from tr(id, ctx).
  232. for (int i = 0; i < p_call->arguments.size(); i++) {
  233. if (p_call->arguments[i]->type == GDScriptParser::Node::LITERAL) {
  234. id_ctx_plural.write[i] = static_cast<GDScriptParser::LiteralNode *>(p_call->arguments[i])->value;
  235. } else {
  236. // Avoid adding something like tr("Flying dragon", var_context_level_1). We want to extract both id and context together.
  237. extract_id_ctx_plural = false;
  238. }
  239. }
  240. if (extract_id_ctx_plural) {
  241. ids_ctx_plural->push_back(id_ctx_plural);
  242. }
  243. } else if (function_name == trn_func) {
  244. // Extract from tr_n(id, plural, n, ctx).
  245. Vector<int> indices;
  246. indices.push_back(0);
  247. indices.push_back(3);
  248. indices.push_back(1);
  249. for (int i = 0; i < indices.size(); i++) {
  250. if (indices[i] >= p_call->arguments.size()) {
  251. continue;
  252. }
  253. if (p_call->arguments[indices[i]]->type == GDScriptParser::Node::LITERAL) {
  254. id_ctx_plural.write[i] = static_cast<GDScriptParser::LiteralNode *>(p_call->arguments[indices[i]])->value;
  255. } else {
  256. extract_id_ctx_plural = false;
  257. }
  258. }
  259. if (extract_id_ctx_plural) {
  260. ids_ctx_plural->push_back(id_ctx_plural);
  261. }
  262. } else if (first_arg_patterns.has(function_name)) {
  263. // Extracting argument with only string literals. In other words, not extracting something like set_text("hello " + some_var).
  264. if (p_call->arguments[0]->type == GDScriptParser::Node::LITERAL) {
  265. ids->push_back(static_cast<GDScriptParser::LiteralNode *>(p_call->arguments[0])->value);
  266. }
  267. } else if (second_arg_patterns.has(function_name)) {
  268. if (p_call->arguments[1]->type == GDScriptParser::Node::LITERAL) {
  269. ids->push_back(static_cast<GDScriptParser::LiteralNode *>(p_call->arguments[1])->value);
  270. }
  271. } else if (function_name == fd_add_filter) {
  272. // Extract the 'JPE Images' in this example - get_node("FileDialog").add_filter("*.jpg; JPE Images").
  273. _extract_fd_literals(p_call->arguments[0]);
  274. } else if (function_name == fd_set_filter && p_call->arguments[0]->type == GDScriptParser::Node::CALL) {
  275. // FileDialog.set_filters() accepts assignment in the form of PackedStringArray. For example,
  276. // get_node("FileDialog").set_filters( PackedStringArray(["*.png ; PNG Images","*.gd ; GDScript Files"])).
  277. GDScriptParser::CallNode *call_node = static_cast<GDScriptParser::CallNode *>(p_call->arguments[0]);
  278. if (call_node->arguments[0]->type == GDScriptParser::Node::ARRAY) {
  279. GDScriptParser::ArrayNode *array_node = static_cast<GDScriptParser::ArrayNode *>(call_node->arguments[0]);
  280. for (int i = 0; i < array_node->elements.size(); i++) {
  281. _extract_fd_literals(array_node->elements[i]);
  282. }
  283. }
  284. }
  285. }
  286. void GDScriptEditorTranslationParserPlugin::_extract_fd_literals(GDScriptParser::ExpressionNode *p_expression) {
  287. // Extract the name in "extension ; name".
  288. if (p_expression->type == GDScriptParser::Node::LITERAL) {
  289. String arg_val = String(static_cast<GDScriptParser::LiteralNode *>(p_expression)->value);
  290. PackedStringArray arr = arg_val.split(";", true);
  291. if (arr.size() != 2) {
  292. ERR_PRINT("Argument for setting FileDialog has bad format.");
  293. return;
  294. }
  295. ids->push_back(arr[1].strip_edges());
  296. }
  297. }
  298. GDScriptEditorTranslationParserPlugin::GDScriptEditorTranslationParserPlugin() {
  299. assignment_patterns.insert("text");
  300. assignment_patterns.insert("placeholder_text");
  301. assignment_patterns.insert("hint_tooltip");
  302. first_arg_patterns.insert("set_text");
  303. first_arg_patterns.insert("set_tooltip");
  304. first_arg_patterns.insert("set_placeholder");
  305. first_arg_patterns.insert("add_tab");
  306. first_arg_patterns.insert("add_check_item");
  307. first_arg_patterns.insert("add_item");
  308. first_arg_patterns.insert("add_multistate_item");
  309. first_arg_patterns.insert("add_radio_check_item");
  310. first_arg_patterns.insert("add_separator");
  311. first_arg_patterns.insert("add_submenu_item");
  312. second_arg_patterns.insert("set_tab_title");
  313. second_arg_patterns.insert("add_icon_check_item");
  314. second_arg_patterns.insert("add_icon_item");
  315. second_arg_patterns.insert("add_icon_radio_check_item");
  316. second_arg_patterns.insert("set_item_text");
  317. }