From e9f6e51fc8bda1824adc403494fb79ce710a006c Mon Sep 17 00:00:00 2001 From: scriptonist Date: Tue, 11 Jun 2019 21:56:28 +0530 Subject: [PATCH] compiler,runtime: implement string to []rune conversion Commit message by aykevl --- compiler/compiler.go | 4 +++- src/runtime/string.go | 15 +++++++++++++++ testdata/{rangestring.go => string.go} | 8 ++++++++ testdata/{rangestring.txt => string.txt} | 9 +++++++++ 4 files changed, 35 insertions(+), 1 deletion(-) rename testdata/{rangestring.go => string.go} (51%) rename testdata/{rangestring.txt => string.txt} (51%) diff --git a/compiler/compiler.go b/compiler/compiler.go index 93c3f496..00e008fb 100644 --- a/compiler/compiler.go +++ b/compiler/compiler.go @@ -2458,8 +2458,10 @@ func (c *Compiler) parseConvert(typeFrom, typeTo types.Type, value llvm.Value, p switch elemType.Kind() { case types.Byte: return c.createRuntimeCall("stringToBytes", []llvm.Value{value}, ""), nil + case types.Rune: + return c.createRuntimeCall("stringToRunes", []llvm.Value{value}, ""), nil default: - return llvm.Value{}, c.makeError(pos, "todo: convert from string: "+elemType.String()) + panic("unexpected type in string to slice conversion") } default: diff --git a/src/runtime/string.go b/src/runtime/string.go index 780c97f4..6d9c3875 100644 --- a/src/runtime/string.go +++ b/src/runtime/string.go @@ -89,6 +89,21 @@ func stringToBytes(x _string) (slice struct { return } +// Convert a string to []rune slice. +func stringToRunes(s string) []rune { + var n = 0 + for range s { + n++ + } + var r = make([]rune, n) + n = 0 + for _, e := range s { + r[n] = e + n++ + } + return r +} + // Create a string from a Unicode code point. func stringFromUnicode(x rune) _string { array, length := encodeUTF8(x) diff --git a/testdata/rangestring.go b/testdata/string.go similarity index 51% rename from testdata/rangestring.go rename to testdata/string.go index 32401c2c..f0aecd07 100644 --- a/testdata/rangestring.go +++ b/testdata/string.go @@ -6,6 +6,14 @@ func testRangeString() { } } +func testStringToRunes() { + var s = "abcü¢€𐍈°x" + for i,c := range []rune(s) { + println(i, c) + } +} + func main() { testRangeString() + testStringToRunes() } diff --git a/testdata/rangestring.txt b/testdata/string.txt similarity index 51% rename from testdata/rangestring.txt rename to testdata/string.txt index e3318b41..b5dca198 100644 --- a/testdata/rangestring.txt +++ b/testdata/string.txt @@ -7,3 +7,12 @@ 10 66376 14 176 16 120 +0 97 +1 98 +2 99 +3 252 +4 162 +5 8364 +6 66376 +7 176 +8 120