Path: blob/master/modules/gdscript/editor/gdscript_translation_parser_plugin.cpp
10278 views
/**************************************************************************/1/* gdscript_translation_parser_plugin.cpp */2/**************************************************************************/3/* This file is part of: */4/* GODOT ENGINE */5/* https://godotengine.org */6/**************************************************************************/7/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */8/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */9/* */10/* Permission is hereby granted, free of charge, to any person obtaining */11/* a copy of this software and associated documentation files (the */12/* "Software"), to deal in the Software without restriction, including */13/* without limitation the rights to use, copy, modify, merge, publish, */14/* distribute, sublicense, and/or sell copies of the Software, and to */15/* permit persons to whom the Software is furnished to do so, subject to */16/* the following conditions: */17/* */18/* The above copyright notice and this permission notice shall be */19/* included in all copies or substantial portions of the Software. */20/* */21/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */22/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */23/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */24/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */25/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */26/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */27/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */28/**************************************************************************/2930#include "gdscript_translation_parser_plugin.h"3132#include "../gdscript.h"33#include "../gdscript_analyzer.h"3435#include "core/io/resource_loader.h"3637void GDScriptEditorTranslationParserPlugin::get_recognized_extensions(List<String> *r_extensions) const {38GDScriptLanguage::get_singleton()->get_recognized_extensions(r_extensions);39}4041Error GDScriptEditorTranslationParserPlugin::parse_file(const String &p_path, Vector<Vector<String>> *r_translations) {42// Extract all translatable strings using the parsed tree from GDScriptParser.43// The strategy is to find all ExpressionNode and AssignmentNode from the tree and extract strings if relevant, i.e44// Search strings in ExpressionNode -> CallNode -> tr(), set_text(), set_placeholder() etc.45// Search strings in AssignmentNode -> text = "__", tooltip_text = "__" etc.4647Error err;48Ref<Resource> loaded_res = ResourceLoader::load(p_path, "", ResourceFormatLoader::CACHE_MODE_REUSE, &err);49ERR_FAIL_COND_V_MSG(err, err, "Failed to load " + p_path);5051translations = r_translations;5253Ref<GDScript> gdscript = loaded_res;54String source_code = gdscript->get_source_code();5556GDScriptParser parser;57err = parser.parse(source_code, p_path, false);58ERR_FAIL_COND_V_MSG(err, err, "Failed to parse GDScript with GDScriptParser.");5960GDScriptAnalyzer analyzer(&parser);61err = analyzer.analyze();62ERR_FAIL_COND_V_MSG(err, err, "Failed to analyze GDScript with GDScriptAnalyzer.");6364comment_data = &parser.comment_data;6566// Traverse through the parsed tree from GDScriptParser.67GDScriptParser::ClassNode *c = parser.get_tree();68_traverse_class(c);6970comment_data = nullptr;7172return OK;73}7475bool GDScriptEditorTranslationParserPlugin::_is_constant_string(const GDScriptParser::ExpressionNode *p_expression) {76ERR_FAIL_NULL_V(p_expression, false);77return p_expression->is_constant && p_expression->reduced_value.is_string();78}7980String GDScriptEditorTranslationParserPlugin::_parse_comment(int p_line, bool &r_skip) const {81// Parse inline comment.82if (comment_data->has(p_line)) {83const String stripped_comment = comment_data->get(p_line).comment.trim_prefix("#").strip_edges();8485if (stripped_comment.begins_with("TRANSLATORS:")) {86return stripped_comment.trim_prefix("TRANSLATORS:").strip_edges(true, false);87}88if (stripped_comment == "NO_TRANSLATE" || stripped_comment.begins_with("NO_TRANSLATE:")) {89r_skip = true;90return String();91}92}9394// Parse multiline comment.95String multiline_comment;96for (int line = p_line - 1; comment_data->has(line) && comment_data->get(line).new_line; line--) {97const String stripped_comment = comment_data->get(line).comment.trim_prefix("#").strip_edges();9899if (stripped_comment.is_empty()) {100continue;101}102103if (multiline_comment.is_empty()) {104multiline_comment = stripped_comment;105} else {106multiline_comment = stripped_comment + "\n" + multiline_comment;107}108109if (stripped_comment.begins_with("TRANSLATORS:")) {110return multiline_comment.trim_prefix("TRANSLATORS:").strip_edges(true, false);111}112if (stripped_comment == "NO_TRANSLATE" || stripped_comment.begins_with("NO_TRANSLATE:")) {113r_skip = true;114return String();115}116}117118return String();119}120121void GDScriptEditorTranslationParserPlugin::_add_id(const String &p_id, int p_line) {122bool skip = false;123const String comment = _parse_comment(p_line, skip);124if (skip) {125return;126}127128translations->push_back({ p_id, String(), String(), comment });129}130131void GDScriptEditorTranslationParserPlugin::_add_id_ctx_plural(const Vector<String> &p_id_ctx_plural, int p_line) {132bool skip = false;133const String comment = _parse_comment(p_line, skip);134if (skip) {135return;136}137138translations->push_back({ p_id_ctx_plural[0], p_id_ctx_plural[1], p_id_ctx_plural[2], comment });139}140141void GDScriptEditorTranslationParserPlugin::_traverse_class(const GDScriptParser::ClassNode *p_class) {142for (int i = 0; i < p_class->members.size(); i++) {143const GDScriptParser::ClassNode::Member &m = p_class->members[i];144// Other member types can't contain translatable strings.145switch (m.type) {146case GDScriptParser::ClassNode::Member::CLASS:147_traverse_class(m.m_class);148break;149case GDScriptParser::ClassNode::Member::FUNCTION:150_traverse_function(m.function);151break;152case GDScriptParser::ClassNode::Member::VARIABLE:153_assess_expression(m.variable->initializer);154if (m.variable->property == GDScriptParser::VariableNode::PROP_INLINE) {155_traverse_function(m.variable->setter);156_traverse_function(m.variable->getter);157}158break;159default:160break;161}162}163}164165void GDScriptEditorTranslationParserPlugin::_traverse_function(const GDScriptParser::FunctionNode *p_func) {166if (!p_func) {167return;168}169170for (int i = 0; i < p_func->parameters.size(); i++) {171_assess_expression(p_func->parameters[i]->initializer);172}173_traverse_block(p_func->body);174}175176void GDScriptEditorTranslationParserPlugin::_traverse_block(const GDScriptParser::SuiteNode *p_suite) {177if (!p_suite) {178return;179}180181const Vector<GDScriptParser::Node *> &statements = p_suite->statements;182for (int i = 0; i < statements.size(); i++) {183const GDScriptParser::Node *statement = statements[i];184185// BREAK, BREAKPOINT, CONSTANT, CONTINUE, and PASS are skipped because they can't contain translatable strings.186switch (statement->type) {187case GDScriptParser::Node::ASSERT: {188const GDScriptParser::AssertNode *assert_node = static_cast<const GDScriptParser::AssertNode *>(statement);189_assess_expression(assert_node->condition);190_assess_expression(assert_node->message);191} break;192case GDScriptParser::Node::ASSIGNMENT: {193_assess_assignment(static_cast<const GDScriptParser::AssignmentNode *>(statement));194} break;195case GDScriptParser::Node::FOR: {196const GDScriptParser::ForNode *for_node = static_cast<const GDScriptParser::ForNode *>(statement);197_assess_expression(for_node->list);198_traverse_block(for_node->loop);199} break;200case GDScriptParser::Node::IF: {201const GDScriptParser::IfNode *if_node = static_cast<const GDScriptParser::IfNode *>(statement);202_assess_expression(if_node->condition);203_traverse_block(if_node->true_block);204_traverse_block(if_node->false_block);205} break;206case GDScriptParser::Node::MATCH: {207const GDScriptParser::MatchNode *match_node = static_cast<const GDScriptParser::MatchNode *>(statement);208_assess_expression(match_node->test);209for (int j = 0; j < match_node->branches.size(); j++) {210_traverse_block(match_node->branches[j]->guard_body);211_traverse_block(match_node->branches[j]->block);212}213} break;214case GDScriptParser::Node::RETURN: {215_assess_expression(static_cast<const GDScriptParser::ReturnNode *>(statement)->return_value);216} break;217case GDScriptParser::Node::VARIABLE: {218_assess_expression(static_cast<const GDScriptParser::VariableNode *>(statement)->initializer);219} break;220case GDScriptParser::Node::WHILE: {221const GDScriptParser::WhileNode *while_node = static_cast<const GDScriptParser::WhileNode *>(statement);222_assess_expression(while_node->condition);223_traverse_block(while_node->loop);224} break;225default: {226if (statement->is_expression()) {227_assess_expression(static_cast<const GDScriptParser::ExpressionNode *>(statement));228}229} break;230}231}232}233234void GDScriptEditorTranslationParserPlugin::_assess_expression(const GDScriptParser::ExpressionNode *p_expression) {235// Explore all ExpressionNodes to find CallNodes which contain translation strings, such as tr(), set_text() etc.236// tr() can be embedded quite deep within multiple ExpressionNodes so need to dig down to search through all ExpressionNodes.237if (!p_expression) {238return;239}240241// GET_NODE, IDENTIFIER, LITERAL, PRELOAD, SELF, and TYPE are skipped because they can't contain translatable strings.242switch (p_expression->type) {243case GDScriptParser::Node::ARRAY: {244const GDScriptParser::ArrayNode *array_node = static_cast<const GDScriptParser::ArrayNode *>(p_expression);245for (int i = 0; i < array_node->elements.size(); i++) {246_assess_expression(array_node->elements[i]);247}248} break;249case GDScriptParser::Node::ASSIGNMENT: {250_assess_assignment(static_cast<const GDScriptParser::AssignmentNode *>(p_expression));251} break;252case GDScriptParser::Node::AWAIT: {253_assess_expression(static_cast<const GDScriptParser::AwaitNode *>(p_expression)->to_await);254} break;255case GDScriptParser::Node::BINARY_OPERATOR: {256const GDScriptParser::BinaryOpNode *binary_op_node = static_cast<const GDScriptParser::BinaryOpNode *>(p_expression);257_assess_expression(binary_op_node->left_operand);258_assess_expression(binary_op_node->right_operand);259} break;260case GDScriptParser::Node::CALL: {261_assess_call(static_cast<const GDScriptParser::CallNode *>(p_expression));262} break;263case GDScriptParser::Node::CAST: {264_assess_expression(static_cast<const GDScriptParser::CastNode *>(p_expression)->operand);265} break;266case GDScriptParser::Node::DICTIONARY: {267const GDScriptParser::DictionaryNode *dict_node = static_cast<const GDScriptParser::DictionaryNode *>(p_expression);268for (int i = 0; i < dict_node->elements.size(); i++) {269_assess_expression(dict_node->elements[i].key);270_assess_expression(dict_node->elements[i].value);271}272} break;273case GDScriptParser::Node::LAMBDA: {274_traverse_function(static_cast<const GDScriptParser::LambdaNode *>(p_expression)->function);275} break;276case GDScriptParser::Node::SUBSCRIPT: {277const GDScriptParser::SubscriptNode *subscript_node = static_cast<const GDScriptParser::SubscriptNode *>(p_expression);278_assess_expression(subscript_node->base);279if (!subscript_node->is_attribute) {280_assess_expression(subscript_node->index);281}282} break;283case GDScriptParser::Node::TERNARY_OPERATOR: {284const GDScriptParser::TernaryOpNode *ternary_op_node = static_cast<const GDScriptParser::TernaryOpNode *>(p_expression);285_assess_expression(ternary_op_node->condition);286_assess_expression(ternary_op_node->true_expr);287_assess_expression(ternary_op_node->false_expr);288} break;289case GDScriptParser::Node::TYPE_TEST: {290_assess_expression(static_cast<const GDScriptParser::TypeTestNode *>(p_expression)->operand);291} break;292case GDScriptParser::Node::UNARY_OPERATOR: {293_assess_expression(static_cast<const GDScriptParser::UnaryOpNode *>(p_expression)->operand);294} break;295default: {296} break;297}298}299300void GDScriptEditorTranslationParserPlugin::_assess_assignment(const GDScriptParser::AssignmentNode *p_assignment) {301_assess_expression(p_assignment->assignee);302_assess_expression(p_assignment->assigned_value);303304// Extract the translatable strings coming from assignments. For example, get_node("Label").text = "____"305306StringName assignee_name;307if (p_assignment->assignee->type == GDScriptParser::Node::IDENTIFIER) {308assignee_name = static_cast<const GDScriptParser::IdentifierNode *>(p_assignment->assignee)->name;309} else if (p_assignment->assignee->type == GDScriptParser::Node::SUBSCRIPT) {310const GDScriptParser::SubscriptNode *subscript = static_cast<const GDScriptParser::SubscriptNode *>(p_assignment->assignee);311if (subscript->is_attribute && subscript->attribute) {312assignee_name = subscript->attribute->name;313} else if (subscript->index && _is_constant_string(subscript->index)) {314assignee_name = subscript->index->reduced_value;315}316}317318if (assignee_name != StringName() && assignment_patterns.has(assignee_name) && _is_constant_string(p_assignment->assigned_value)) {319// 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.320_add_id(p_assignment->assigned_value->reduced_value, p_assignment->assigned_value->start_line);321} else if (assignee_name == fd_filters) {322// Extract from `get_node("FileDialog").filters = <filter array>`.323_extract_fd_filter_array(p_assignment->assigned_value);324}325}326327void GDScriptEditorTranslationParserPlugin::_assess_call(const GDScriptParser::CallNode *p_call) {328_assess_expression(p_call->callee);329for (int i = 0; i < p_call->arguments.size(); i++) {330_assess_expression(p_call->arguments[i]);331}332333// Extract the translatable strings coming from function calls. For example:334// tr("___"), get_node("Label").set_text("____"), get_node("LineEdit").set_placeholder("____").335336StringName function_name = p_call->function_name;337338// Variables for extracting tr() and tr_n().339Vector<String> id_ctx_plural;340id_ctx_plural.resize(3);341bool extract_id_ctx_plural = true;342343if (function_name == tr_func || function_name == atr_func) {344// Extract from `tr(id, ctx)` or `atr(id, ctx)`.345for (int i = 0; i < p_call->arguments.size(); i++) {346if (_is_constant_string(p_call->arguments[i])) {347id_ctx_plural.write[i] = p_call->arguments[i]->reduced_value;348} else {349// Avoid adding something like tr("Flying dragon", var_context_level_1). We want to extract both id and context together.350extract_id_ctx_plural = false;351}352}353if (extract_id_ctx_plural) {354_add_id_ctx_plural(id_ctx_plural, p_call->start_line);355}356} else if (function_name == trn_func || function_name == atrn_func) {357// Extract from `tr_n(id, plural, n, ctx)` or `atr_n(id, plural, n, ctx)`.358Vector<int> indices;359indices.push_back(0);360indices.push_back(3);361indices.push_back(1);362for (int i = 0; i < indices.size(); i++) {363if (indices[i] >= p_call->arguments.size()) {364continue;365}366367if (_is_constant_string(p_call->arguments[indices[i]])) {368id_ctx_plural.write[i] = p_call->arguments[indices[i]]->reduced_value;369} else {370extract_id_ctx_plural = false;371}372}373if (extract_id_ctx_plural) {374_add_id_ctx_plural(id_ctx_plural, p_call->start_line);375}376} else if (first_arg_patterns.has(function_name)) {377if (!p_call->arguments.is_empty() && _is_constant_string(p_call->arguments[0])) {378_add_id(p_call->arguments[0]->reduced_value, p_call->arguments[0]->start_line);379}380} else if (second_arg_patterns.has(function_name)) {381if (p_call->arguments.size() > 1 && _is_constant_string(p_call->arguments[1])) {382_add_id(p_call->arguments[1]->reduced_value, p_call->arguments[1]->start_line);383}384} else if (function_name == fd_add_filter) {385// Extract the 'JPE Images' in this example - get_node("FileDialog").add_filter("*.jpg; JPE Images").386if (!p_call->arguments.is_empty()) {387_extract_fd_filter_string(p_call->arguments[0], p_call->arguments[0]->start_line);388}389} else if (function_name == fd_set_filter) {390// Extract from `get_node("FileDialog").set_filters(<filter array>)`.391if (!p_call->arguments.is_empty()) {392_extract_fd_filter_array(p_call->arguments[0]);393}394}395}396397void GDScriptEditorTranslationParserPlugin::_extract_fd_filter_string(const GDScriptParser::ExpressionNode *p_expression, int p_line) {398// Extract the name in "extension ; name".399if (_is_constant_string(p_expression)) {400PackedStringArray arr = p_expression->reduced_value.operator String().split(";", true);401ERR_FAIL_COND_MSG(arr.size() != 2, "Argument for setting FileDialog has bad format.");402_add_id(arr[1].strip_edges(), p_line);403}404}405406void GDScriptEditorTranslationParserPlugin::_extract_fd_filter_array(const GDScriptParser::ExpressionNode *p_expression) {407const GDScriptParser::ArrayNode *array_node = nullptr;408409if (p_expression->type == GDScriptParser::Node::ARRAY) {410// Extract from `["*.png ; PNG Images","*.gd ; GDScript Files"]` (implicit cast to `PackedStringArray`).411array_node = static_cast<const GDScriptParser::ArrayNode *>(p_expression);412} else if (p_expression->type == GDScriptParser::Node::CALL) {413// Extract from `PackedStringArray(["*.png ; PNG Images","*.gd ; GDScript Files"])`.414const GDScriptParser::CallNode *call_node = static_cast<const GDScriptParser::CallNode *>(p_expression);415if (call_node->get_callee_type() == GDScriptParser::Node::IDENTIFIER && call_node->function_name == SNAME("PackedStringArray") && !call_node->arguments.is_empty() && call_node->arguments[0]->type == GDScriptParser::Node::ARRAY) {416array_node = static_cast<const GDScriptParser::ArrayNode *>(call_node->arguments[0]);417}418}419420if (array_node) {421for (int i = 0; i < array_node->elements.size(); i++) {422_extract_fd_filter_string(array_node->elements[i], array_node->elements[i]->start_line);423}424}425}426427GDScriptEditorTranslationParserPlugin::GDScriptEditorTranslationParserPlugin() {428assignment_patterns.insert("text");429assignment_patterns.insert("placeholder_text");430assignment_patterns.insert("tooltip_text");431432first_arg_patterns.insert("set_text");433first_arg_patterns.insert("set_tooltip_text");434first_arg_patterns.insert("set_placeholder");435first_arg_patterns.insert("add_tab");436first_arg_patterns.insert("add_check_item");437first_arg_patterns.insert("add_item");438first_arg_patterns.insert("add_multistate_item");439first_arg_patterns.insert("add_radio_check_item");440first_arg_patterns.insert("add_separator");441first_arg_patterns.insert("add_submenu_item");442443second_arg_patterns.insert("set_tab_title");444second_arg_patterns.insert("add_icon_check_item");445second_arg_patterns.insert("add_icon_item");446second_arg_patterns.insert("add_icon_radio_check_item");447second_arg_patterns.insert("set_item_text");448}449450451