gdscript_translation_parser_plugin.cpp 18 KB

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