diff --git a/tests/stdio.c b/tests/stdio.c index 5ad990178..fe1105a9e 100644 --- a/tests/stdio.c +++ b/tests/stdio.c @@ -12,7 +12,7 @@ test_##t(); // size of that file -int filesize = 9699; +int filesize = 9979; void test_putchar() { @@ -46,6 +46,17 @@ void test_printf() printf("# Width trick: %*d \n", 5, 10); printf("# %s \n", "A string"); + + int magnitude = 4; + char printfFormat[30] = "%0"; + char magnitudeString[10]; + sprintf(magnitudeString, "%d", magnitude); + strcat(printfFormat, magnitudeString); + strcat(printfFormat, "d "); + printf("# "); + printf(printfFormat, 120); + printf(" \n"); + pass("%s", "printf"); } diff --git a/transpiler/literals.go b/transpiler/literals.go index 0ec676414..e94096cb9 100644 --- a/transpiler/literals.go +++ b/transpiler/literals.go @@ -4,6 +4,7 @@ package transpiler import ( + "bytes" "fmt" "go/token" @@ -13,6 +14,7 @@ import ( "github.com/elliotchance/c2go/ast" "github.com/elliotchance/c2go/program" + "github.com/elliotchance/c2go/types" "github.com/elliotchance/c2go/util" ) @@ -21,8 +23,19 @@ func transpileFloatingLiteral(n *ast.FloatingLiteral) *goast.BasicLit { } func transpileStringLiteral(n *ast.StringLiteral) goast.Expr { + // Example: + // StringLiteral 0x280b918 'char [30]' lvalue "%0" + s, err := types.GetAmountArraySize(n.Type) + if err != nil { + return util.NewCallExpr("[]byte", + util.NewStringLit(strconv.Quote(n.Value+"\x00"))) + } + buf := bytes.NewBufferString(n.Value + "\x00") + if buf.Len() < s { + buf.Write(make([]byte, s-buf.Len())) + } return util.NewCallExpr("[]byte", - util.NewStringLit(strconv.Quote(n.Value+"\x00"))) + util.NewStringLit(strconv.Quote(buf.String()))) } func transpileIntegerLiteral(n *ast.IntegerLiteral) *goast.BasicLit { diff --git a/types/resolve.go b/types/resolve.go index 6c9f3becf..48534bf59 100644 --- a/types/resolve.go +++ b/types/resolve.go @@ -3,6 +3,7 @@ package types import ( "errors" "fmt" + "strconv" "strings" "github.com/elliotchance/c2go/program" @@ -455,3 +456,26 @@ func GenerateCorrectType(name string) string { return out } + +// GetAmountArraySize - return amount array size +// Example : +// In : 'char [40]' +// Out : 40 +func GetAmountArraySize(cType string) (size int, err error) { + reg := util.GetRegex("\\[(?P\\d+)\\]") + match := reg.FindStringSubmatch(cType) + + if reg.NumSubexp() != 1 { + err = fmt.Errorf("Cannot found size of array in type : %s", cType) + return + } + + result := make(map[string]string) + for i, name := range reg.SubexpNames() { + if i != 0 { + result[name] = match[i] + } + } + + return strconv.Atoi(result["size"]) +}