diff options
| author | George Marques <george@gmarqu.es> | 2024-04-09 15:49:44 -0300 |
|---|---|---|
| committer | George Marques <george@gmarqu.es> | 2024-04-10 11:49:30 -0300 |
| commit | 4bdba718c5fcb2bd58827b8ede3ea7d0c4251fbd (patch) | |
| tree | 3e305305c2b3506d486322a4521ff3dd7943348d /modules/gdscript | |
| parent | a7b860250f305f6cbaf61c30f232ff3bbdfdda0b (diff) | |
| download | redot-engine-4bdba718c5fcb2bd58827b8ede3ea7d0c4251fbd.tar.gz | |
GDScript: Infer type with string format operator
If the left value type is known to be String, assume the format operator
(`%`) will return a string, since it works with any type in the right
hand side. This is also used by type inference even if the right hand
type is unknown at compile time.
Diffstat (limited to 'modules/gdscript')
3 files changed, 13 insertions, 0 deletions
diff --git a/modules/gdscript/gdscript_analyzer.cpp b/modules/gdscript/gdscript_analyzer.cpp index f67f4913c3..1c768006ee 100644 --- a/modules/gdscript/gdscript_analyzer.cpp +++ b/modules/gdscript/gdscript_analyzer.cpp @@ -2846,6 +2846,11 @@ void GDScriptAnalyzer::reduce_binary_op(GDScriptParser::BinaryOpNode *p_binary_o result.type_source = GDScriptParser::DataType::ANNOTATED_EXPLICIT; result.kind = GDScriptParser::DataType::BUILTIN; result.builtin_type = Variant::BOOL; + } else if (p_binary_op->variant_op == Variant::OP_MODULE && left_type.builtin_type == Variant::STRING) { + // The modulo operator (%) on string acts as formatting and will always return a string. + result.type_source = left_type.type_source; + result.kind = GDScriptParser::DataType::BUILTIN; + result.builtin_type = Variant::STRING; } else if (left_type.is_variant() || right_type.is_variant()) { // Cannot infer type because one operand can be anything. result.kind = GDScriptParser::DataType::VARIANT; diff --git a/modules/gdscript/tests/scripts/analyzer/features/infer_type_on_string_format.gd b/modules/gdscript/tests/scripts/analyzer/features/infer_type_on_string_format.gd new file mode 100644 index 0000000000..c83a3a8a14 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/infer_type_on_string_format.gd @@ -0,0 +1,6 @@ +# GH-88082 + +func test(): + var x = 1 + var message := "value: %s" % x + print(message) diff --git a/modules/gdscript/tests/scripts/analyzer/features/infer_type_on_string_format.out b/modules/gdscript/tests/scripts/analyzer/features/infer_type_on_string_format.out new file mode 100644 index 0000000000..cf6464a4c3 --- /dev/null +++ b/modules/gdscript/tests/scripts/analyzer/features/infer_type_on_string_format.out @@ -0,0 +1,2 @@ +GDTEST_OK +value: 1 |
