diff --git a/backend_wat.go b/backend_wat.go index 9b2e205..f98421b 100644 --- a/backend_wat.go +++ b/backend_wat.go @@ -4,6 +4,7 @@ import ( "errors" "log" "strconv" + "unicode" ) func getPrimitiveWATType(primitive PrimitiveType) string { @@ -34,6 +35,20 @@ func getWATType(t Type) string { return getPrimitiveWATType(primitive) } +func safeASCIIIdentifier(identifier string) string { + ascii := "" + for _, rune := range identifier { + if rune < unicode.MaxASCII && (unicode.IsLetter(rune) || unicode.IsDigit(rune)) { + ascii += string(rune) + continue + } + + ascii += "$" + strconv.Itoa(int(rune)) + } + + return ascii +} + func getTypeCast(primitive PrimitiveType) string { switch primitive { case Primitive_I8: @@ -323,7 +338,7 @@ func compileBlockWAT(block Block) (string, error) { } func compileFunctionWAT(function ParsedFunction) (string, error) { - funcWAT := "(func $" + function.Name + "\n" + funcWAT := "(func $" + safeASCIIIdentifier(function.Name) + "\n" for _, local := range function.Locals { if !local.IsParameter { @@ -359,7 +374,7 @@ func compileFunctionWAT(function ParsedFunction) (string, error) { funcWAT += wat - return funcWAT + ") (export \"" + function.Name + "\" (func $" + function.Name + "))\n", nil + return funcWAT + ") (export \"" + function.Name + "\" (func $" + safeASCIIIdentifier(function.Name) + "))\n", nil } func backendWAT(file ParsedFile) (string, error) { diff --git a/example/add.lang b/example/add.lang index 27b6393..a30748c 100644 --- a/example/add.lang +++ b/example/add.lang @@ -2,7 +2,7 @@ u64 add(u8 a, u8 b) { return add(a - 1u8, a); } -u64 add2(u64 a, u64 b) { +u64 addわ(u64 a, u64 b) { return a + b; }