v.checker: restrict `x T` in `fn test<T>(x T){ unsafe{ println(x[0]) }`, but allow `x &T`

pull/10400/head
Delyan Angelov 2021-06-09 12:05:46 +03:00
parent f351ff037e
commit 115edff7e9
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
3 changed files with 25 additions and 1 deletions

View File

@ -6510,10 +6510,16 @@ pub fn (mut c Checker) index_expr(mut node ast.IndexExpr) ast.Type {
break break
} }
.any { .any {
gname := typ_sym.name
typ = c.unwrap_generic(typ) typ = c.unwrap_generic(typ)
node.left_type = typ node.left_type = typ
typ_sym = c.table.get_final_type_symbol(typ) typ_sym = c.table.get_final_type_symbol(typ)
if typ.is_ptr() {
continue continue
} else {
c.error('generic type $gname does not support indexing, pass an array, or a reference instead, e.g. []$gname or &$gname',
node.pos)
}
} }
else { else {
break break

View File

@ -0,0 +1,6 @@
vlib/v/checker/tests/generic_param_used_as_an_array_err.vv:2:10: error: generic type T does not support indexing, pass an array, or a reference instead, e.g. []T or &T
1 | fn test<T>(arr T) {
2 | a := arr[1]
| ~~~
3 | println(a)
4 | }

View File

@ -0,0 +1,12 @@
fn test<T>(arr T) {
a := arr[1]
println(a)
}
fn main() {
a := [1, 2, 3]!
test(a)
b := ['a', 'b', 'c']!
test(b)
}