From 63032c4bb70d9c86348ac9540fd91b01acc3a4c0 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Sat, 7 Mar 2020 16:23:10 +0100 Subject: [PATCH] cgen: minor fixes --- vlib/builtin/string.v | 2 +- vlib/v/ast/ast.v | 14 ++++++++------ vlib/v/gen/cgen.v | 19 +++++++++++++++---- vlib/v/parser/parser.v | 9 +++++++-- 4 files changed, 31 insertions(+), 13 deletions(-) diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index 4f26446c7f..a784405780 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -1208,7 +1208,7 @@ pub fn (s string) reverse() string { str: malloc(s.len) } for i := s.len - 1; i >= 0; i-- { - res[s.len - i - 1] = s[i] + res.str[s.len - i - 1] = s[i] } return res } diff --git a/vlib/v/ast/ast.v b/vlib/v/ast/ast.v index 086ac8a5ad..307d92a6a6 100644 --- a/vlib/v/ast/ast.v +++ b/vlib/v/ast/ast.v @@ -490,11 +490,11 @@ mut: pub struct MapInit { pub: - pos token.Position - keys []Expr - vals []Expr + pos token.Position + keys []Expr + vals []Expr mut: - typ table.Type + typ table.Type key_type table.Type value_type table.Type } @@ -510,8 +510,10 @@ pub: pub struct CastExpr { pub: - typ table.Type - expr Expr + typ table.Type + expr Expr // `buf` + arg Expr // `n` in `string(buf, n)` + has_arg bool } pub struct AssertStmt { diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 9fb7da5560..ae3be96b23 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -415,10 +415,21 @@ fn (g mut Gen) expr(node ast.Expr) { } ast.CastExpr { - styp := g.table.type_to_str(it.typ) - g.write('($styp)(') - g.expr(it.expr) - g.write(')') + if it.typ == table.string_type_idx { + g.write('tos(') + g.expr(it.expr) + if it.has_arg { + g.write(',') + g.expr(it.arg) + } + g.write(')') + } + else { + styp := g.table.type_to_str(it.typ) + g.write('($styp)(') + g.expr(it.expr) + g.write(')') + } } ast.CharLiteral { g.write("'$it.val'") diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index aaecf35fc4..013558ca88 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -530,7 +530,7 @@ pub fn (p mut Parser) name_expr() ast.Expr { // `map[string]int` initialization if p.tok.lit == 'map' && p.peek_tok.kind == .lsbr { map_type := p.parse_map_type() - return ast.MapInit { + return ast.MapInit{ typ: map_type } } @@ -562,16 +562,21 @@ pub fn (p mut Parser) name_expr() ast.Expr { to_typ := p.parse_type() p.check(.lpar) mut expr := ast.Expr{} + mut arg := ast.Expr{} + mut has_arg := false expr = p.expr(0) // TODO, string(b, len) if p.tok.kind == .comma && table.type_idx(to_typ) == table.string_type_idx { p.check(.comma) - p.expr(0) // len + arg = p.expr(0) // len + has_arg = true } p.check(.rpar) node = ast.CastExpr{ typ: to_typ expr: expr + arg: arg + has_arg: has_arg } p.expr_mod = '' return node