checker: check string(1) cast error

pull/4752/head
yuyi 2020-05-06 18:05:24 +08:00 committed by GitHub
parent 5bd3045498
commit 51f3f31a4e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 21 additions and 3 deletions

View File

@ -678,7 +678,7 @@ pub:
expr Expr // `buf`
arg Expr // `n` in `string(buf, n)`
typ table.Type // `string`
pos token.Position
pos token.Position
mut:
typname string
expr_type table.Type // `byteptr`
@ -777,7 +777,9 @@ fn (expr Expr) position() token.Position {
AssignExpr {
return it.pos
}
// ast.CastExpr { }
CastExpr {
return it.pos
}
Assoc {
return it.pos
}

View File

@ -1560,6 +1560,12 @@ pub fn (mut c Checker) expr(node ast.Expr) table.Type {
}
ast.CastExpr {
it.expr_type = c.expr(it.expr)
sym := c.table.get_type_symbol(it.expr_type)
if it.typ == table.string_type && !(sym.kind in [.byte, .byteptr] ||
sym.kind == .array && sym.name == 'array_byte') {
type_name := c.table.type_to_str(it.expr_type)
c.error('cannot cast type `$type_name` to string', it.pos)
}
if it.has_arg {
c.expr(it.arg)
}

View File

@ -0,0 +1,6 @@
vlib/v/checker/tests/cast_string_err.v:2:14: error: cannot cast type `int` to string
1 | fn main() {
2 | a := string(1)
| ^
3 | println(a)
4 | }

View File

@ -0,0 +1,4 @@
fn main() {
a := string(1)
println(a)
}

View File

@ -674,7 +674,7 @@ pub fn (mut p Parser) name_expr() ast.Expr {
expr: expr
arg: arg
has_arg: has_arg
pos: p.tok.position()
pos: expr.position()
}
p.expr_mod = ''
return node