cgen: generate str function when using x.str()

pull/4614/head
yuyi 2020-04-27 14:09:37 +08:00 committed by GitHub
parent 3256d060f7
commit 95754f211f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 40 additions and 24 deletions

View File

@ -274,6 +274,9 @@ fn (mut g Gen) method_call(node ast.CallExpr) {
g.gen_filter(node)
return
}
if node.name == 'str' && !typ_sym.has_method('str') {
g.gen_str_for_type(node.receiver_type)
}
// TODO performance, detect `array` method differently
if typ_sym.kind == .array && node.name in ['repeat', 'sort_with_compare', 'free', 'push_many',
'trim',

View File

@ -1,12 +1,33 @@
fn test_array_to_string_conversion() {
expected := '["1", "2", "3", "4"]'
arr := ['1', '2', '3', '4']
assert arr.str() == expected
a := ['1', '2', '3', '4']
assert a.str() == '["1", "2", "3", "4"]'
b := [1, 2, 3, 4]
assert b.str() == '[1, 2, 3, 4]'
c := [1.1, 2.2, 3.3, 4.4]
assert c.str() == '[1.1, 2.2, 3.3, 4.4]'
d := [i16(1), 2, 3]
assert d.str() == '[1, 2, 3]'
e := [i64(1), 2, 3]
assert e.str() == '[1, 2, 3]'
}
fn test_interpolation_array_to_string() {
a := ['1', '2', '3']
assert '$a' == '["1", "2", "3"]'
b := ['a', 'b']
assert '$b' == '["a", "b"]'
b := [1, 2, 3, 4]
assert '$b' == '[1, 2, 3, 4]'
c := [1.1, 2.2, 3.3, 4.4]
assert '$c' == '[1.1, 2.2, 3.3, 4.4]'
d := [i16(1), 2, 3]
assert '$d' == '[1, 2, 3]'
e := [i64(1), 2, 3]
assert '$e' == '[1, 2, 3]'
}

View File

@ -1,63 +1,55 @@
struct Foo {
number int
str string
f f64
}
fn test_array_str() {
f := Foo{34, 'hello', 1.2}
println(f)
// s := f.str()
// println(s)
n := [1, 2, 3]
assert n.str() == '[1, 2, 3]'
println(n) // make sure the array is printable
n2 := [4, 5, 6]
// assert n2.str() == '[4, 5, 6]'
println(n2)
}
fn test_array_of_floats() {
// f64 array
aa := [1.2, 3.4, 5.67]
assert aa.str() == '[1.2, 3.4, 5.67]'
assert '$aa' == '[1.2, 3.4, 5.67]'
// f32 array
bb := [f32(1.2), 3.4, 5.67]
assert bb.str() == '[1.2, 3.4, 5.67]'
assert '$bb' == '[1.2, 3.4, 5.67]'
}
fn test_array_of_bools() {
aa := [true, false, true]
assert aa.str() == '[true, false, true]'
assert '$aa' == '[true, false, true]'
}
fn test_array_of_ints() {
// int
a1 := [11, 22, 33]
assert a1.str() == '[11, 22, 33]'
assert '$a1' == '[11, 22, 33]'
// u32
a2 := [u32(11), 22, 33]
assert a2.str() == '[11, 22, 33]'
assert '$a2' == '[11, 22, 33]'
// i16
b1 := [i16(11), 22, 33]
assert b1.str() == '[11, 22, 33]'
assert '$b1' == '[11, 22, 33]'
// u16
b2 := [u16(11), 22, 33]
assert b2.str() == '[11, 22, 33]'
assert '$b2' == '[11, 22, 33]'
// i64
c1 := [i64(11), 22, 33]
assert c1.str() == '[11, 22, 33]'
assert '$c1' == '[11, 22, 33]'
// u64
c2 := [u64(11), 22, 33]
assert c2.str() == '[11, 22, 33]'
assert '$c2' == '[11, 22, 33]'
}
fn test_array_of_bytes() {
aa := [`a`, `b`, `c`]
assert aa.str() == '[a, b, c]'
assert '$aa' == '[a, b, c]'
}
fn test_array_of_strings() {
aa := ['aa', 'bb', 'cc']
assert aa.str() == '["aa", "bb", "cc"]'
assert '$aa' == '["aa", "bb", "cc"]'
}