all: support map[f32]string and map[f64]string (float map keys) too (#8556)

pull/8561/head
Delyan Angelov 2021-02-05 00:59:49 +02:00 committed by GitHub
parent 97e36cd97a
commit 119dfc0bb0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 31 additions and 7 deletions

View File

@ -0,0 +1,27 @@
fn test_map_of_f32() {
mut m32 := map[f32]string{}
m32[1.0] = 'one'
println(m32)
assert '$m32' == r"{1.: 'one'}"
for k, v in m32 {
assert typeof(k).name == 'f32'
assert typeof(v).name == 'string'
assert k == 1.0
assert v == 'one'
}
}
fn test_map_of_f64() {
mut m64 := {
3.14: 'pi'
}
m64[1.0] = 'one'
println(m64)
assert '$m64' == r"{3.14: 'pi', 1.: 'one'}"
for k, v in m64 {
assert typeof(k).name == 'f64'
assert typeof(v).name == 'string'
assert k in [1.0, 3.14]
assert v in ['pi', 'one']
}
}

View File

@ -2471,7 +2471,7 @@ fn (mut g Gen) map_fn_ptrs(key_typ table.TypeSymbol) (string, string, string, st
key_eq_fn = '&map_eq_int_2'
clone_fn = '&map_clone_int_2'
}
.int, .u32, .rune {
.int, .u32, .rune, .f32 {
hash_fn = '&map_hash_int_4'
key_eq_fn = '&map_eq_int_4'
clone_fn = '&map_clone_int_4'
@ -2484,7 +2484,7 @@ fn (mut g Gen) map_fn_ptrs(key_typ table.TypeSymbol) (string, string, string, st
}
return g.map_fn_ptrs(ts)
}
.u64, .i64 {
.u64, .i64, .f64 {
hash_fn = '&map_hash_int_8'
key_eq_fn = '&map_eq_int_8'
clone_fn = '&map_clone_int_8'

View File

@ -158,9 +158,6 @@ fn (mut p Parser) map_init() ast.MapInit {
mut vals := []ast.Expr{}
for p.tok.kind != .rcbr && p.tok.kind != .eof {
key := p.expr(0)
if key is ast.FloatLiteral {
p.error_with_pos('maps do not support floating point keys yet', key.pos)
}
keys << key
p.check(.colon)
val := p.expr(0)

View File

@ -78,9 +78,9 @@ pub fn (mut p Parser) parse_map_type() table.Type {
return 0
}
if !(key_type in [table.string_type_idx, table.voidptr_type_idx]
|| (key_type.is_int() && !key_type.is_ptr())) {
|| ((key_type.is_int() || key_type.is_float())&& !key_type.is_ptr())) {
s := p.table.type_to_str(key_type)
p.error_with_pos('maps only support string, integer, rune or voidptr keys for now (not `$s`)',
p.error_with_pos('maps only support string, integer, float, rune or voidptr keys for now (not `$s`)',
p.tok.position())
return 0
}