1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

checker: add more checks for index_expr (#6737)

This commit is contained in:
Swastik Baranwal 2020-11-07 19:25:05 +05:30 committed by GitHub
parent 125650c986
commit 6354fa031c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 45 additions and 4 deletions

View File

@ -3835,10 +3835,15 @@ fn (mut c Checker) check_index_type(typ_sym &table.TypeSymbol, index_type table.
// println('index expr left=$typ_sym.source_name $node.pos.line_nr')
// if typ_sym.kind == .array && (!(table.type_idx(index_type) in table.number_type_idxs) &&
// index_type_sym.kind != .enum_) {
if typ_sym.kind in [.array, .array_fixed] && !(index_type.is_number() || index_type_sym.kind ==
.enum_) {
c.error('non-integer index `$index_type_sym.source_name` (array type `$typ_sym.source_name`)',
pos)
if typ_sym.kind in [.array, .array_fixed, .string, .ustring] {
if !(index_type.is_number() || index_type_sym.kind == .enum_) {
type_str := if typ_sym.kind in [.string, .ustring] { 'non-integer string index `$index_type_sym.source_name`' } else { 'non-integer index `$index_type_sym.source_name` (array type `$typ_sym.source_name`)' }
c.error('$type_str', pos)
}
if index_type.has_flag(.optional) {
type_str := if typ_sym.kind in [.string, .ustring] { '(type `$typ_sym.source_name`)' } else { '(array type `$typ_sym.source_name`)' }
c.error('cannot use optional as index $type_str', pos)
}
}
}

View File

@ -0,0 +1,6 @@
vlib/v/checker/tests/optional_index_err.vv:3:14: error: cannot use optional as index (type `string`)
1 | fn main() {
2 | v := 'hello'
3 | println(v[v.last_index('l')])
| ~~~~~~~~~~~~~~~~~~~
4 | }

View File

@ -0,0 +1,4 @@
fn main() {
v := 'hello'
println(v[v.last_index('l')])
}

View File

@ -0,0 +1,20 @@
vlib/v/checker/tests/string_index_non_int_err.vv:3:14: error: non-integer string index `string`
1 | fn main() {
2 | v := 'foo'
3 | println(v['f'])
| ~~~~~
4 | println(v[true])
5 | println(v[[23]])
vlib/v/checker/tests/string_index_non_int_err.vv:4:14: error: non-integer string index `bool`
2 | v := 'foo'
3 | println(v['f'])
4 | println(v[true])
| ~~~~~~
5 | println(v[[23]])
6 | }
vlib/v/checker/tests/string_index_non_int_err.vv:5:14: error: non-integer string index `[]int`
3 | println(v['f'])
4 | println(v[true])
5 | println(v[[23]])
| ~~~~~~
6 | }

View File

@ -0,0 +1,6 @@
fn main() {
v := 'foo'
println(v['f'])
println(v[true])
println(v[[23]])
}