Skip to content

Commit

Permalink
GoTranslator: fix problem with % in the raw string segment in f-str…
Browse files Browse the repository at this point in the history
…ings; modified common test to accommodate this pattern
  • Loading branch information
GreyCat committed Mar 1, 2024
1 parent 2cf6676 commit fa8e5c6
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -682,17 +682,17 @@ class TranslatorSpec extends AnyFunSuite {
PythonCompiler -> "u\"abc\""
), CalcStrType)

full("f\"abc{1}def\"", CalcIntType, CalcStrType, Map[LanguageCompilerStatic, String](
CppCompiler -> "std::string(\"abc\") + kaitai::kstream::to_string(1) + std::string(\"def\")",
CSharpCompiler -> "\"abc\" + Convert.ToString((long) (1), 10) + \"def\"",
GoCompiler -> "fmt.Sprintf(\"abc%vdef\", 1)",
JavaCompiler -> "\"abc\" + Long.toString(1, 10) + \"def\"",
JavaScriptCompiler -> "\"abc\" + (1).toString(10) + \"def\"",
LuaCompiler -> "\"abc\" + tostring(1) + \"def\"",
PerlCompiler -> "\"abc\" . sprintf('%d', 1) . \"def\"",
PHPCompiler -> "\"abc\" . strval(1) . \"def\"",
PythonCompiler -> "u\"abc\" + str(1) + u\"def\"",
RubyCompiler -> "\"abc\" + 1.to_s(10) + \"def\"",
full("f\"abc{1}%def\"", CalcIntType, CalcStrType, Map[LanguageCompilerStatic, String](
CppCompiler -> "std::string(\"abc\") + kaitai::kstream::to_string(1) + std::string(\"%def\")",
CSharpCompiler -> "\"abc\" + Convert.ToString((long) (1), 10) + \"%def\"",
GoCompiler -> "fmt.Sprintf(\"abc%v%%def\", 1)",
JavaCompiler -> "\"abc\" + Long.toString(1, 10) + \"%def\"",
JavaScriptCompiler -> "\"abc\" + (1).toString(10) + \"%def\"",
LuaCompiler -> "\"abc\" + tostring(1) + \"%def\"",
PerlCompiler -> "\"abc\" . sprintf('%d', 1) . \"\\%def\"",
PHPCompiler -> "\"abc\" . strval(1) . \"%def\"",
PythonCompiler -> "u\"abc\" + str(1) + u\"%def\"",
RubyCompiler -> "\"abc\" + 1.to_s(10) + \"%def\"",
))

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -481,8 +481,12 @@ class GoTranslator(out: StringLanguageOutputWriter, provider: TypeProvider, impo
importList.add("fmt")

val piecesAndArgs: Seq[(String, Option[String])] = exprs.map {
case Ast.expr.Str(s) => (doStringLiteralBody(s), None)
case e => ("%v", Some(translate(e)))
case Ast.expr.Str(s) =>
// This string will be used as format string, so we need to escape all `%` as `%%`
val escapedFmtStr = s.replace("%", "%%")
(doStringLiteralBody(escapedFmtStr), None)
case e =>
("%v", Some(translate(e)))
}

val fmtString = piecesAndArgs.map(x => x._1).mkString
Expand Down

0 comments on commit fa8e5c6

Please sign in to comment.