From a8b0dfb38ada784c454114c53a423e2082a355a0 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Thu, 25 Jun 2020 14:55:53 +0200 Subject: [PATCH] checker: allow casting strings to string aliases --- vlib/v/ast/ast.v | 2 +- vlib/v/checker/checker.v | 15 +++++++++------ 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/vlib/v/ast/ast.v b/vlib/v/ast/ast.v index 8c665187f7..6593f3684d 100644 --- a/vlib/v/ast/ast.v +++ b/vlib/v/ast/ast.v @@ -703,7 +703,7 @@ pub struct CastExpr { pub: expr Expr // `buf` arg Expr // `n` in `string(buf, n)` - typ table.Type // `string` + typ table.Type // `string` TODO rename to `type_to_cast_to` pos token.Position pub mut: typname string diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index 0c5008b255..8b52a5e0b2 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -1962,14 +1962,17 @@ pub fn (mut c Checker) expr(node ast.Expr) table.Type { node.pos) } if node.expr_type == table.string_type { - mut error_msg := 'cannot cast a string' - if node.expr is ast.StringLiteral { - str_lit := node.expr as ast.StringLiteral - if str_lit.val.len == 1 { - error_msg += ", for denoting characters use `$str_lit.val` instead of '$str_lit.val'" + cast_to_type_sym := c.table.get_type_symbol(node.typ) + if cast_to_type_sym.kind != .alias { + mut error_msg := 'cannot cast a string' + if node.expr is ast.StringLiteral { + str_lit := node.expr as ast.StringLiteral + if str_lit.val.len == 1 { + error_msg += ", for denoting characters use `$str_lit.val` instead of '$str_lit.val'" + } } + c.error(error_msg, node.pos) } - c.error(error_msg, node.pos) } if node.has_arg { c.expr(node.arg)