Skip to content

Commit

Permalink
checker: add more checks for index_expr (#6737)
Browse files Browse the repository at this point in the history
  • Loading branch information
Delta456 committed Nov 7, 2020
1 parent 125650c commit 6354fa0
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 4 deletions.
13 changes: 9 additions & 4 deletions vlib/v/checker/checker.v
Expand Up @@ -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)
}
}
}

Expand Down
6 changes: 6 additions & 0 deletions vlib/v/checker/tests/optional_index_err.out
@@ -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 | }
4 changes: 4 additions & 0 deletions vlib/v/checker/tests/optional_index_err.vv
@@ -0,0 +1,4 @@
fn main() {
v := 'hello'
println(v[v.last_index('l')])
}
20 changes: 20 additions & 0 deletions vlib/v/checker/tests/string_index_non_int_err.out
@@ -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 | }
6 changes: 6 additions & 0 deletions vlib/v/checker/tests/string_index_non_int_err.vv
@@ -0,0 +1,6 @@
fn main() {
v := 'foo'
println(v['f'])
println(v[true])
println(v[[23]])
}

0 comments on commit 6354fa0

Please sign in to comment.