diff --git a/vlib/v/ast/ast.v b/vlib/v/ast/ast.v index 0009796515..4ce46fad4e 100644 --- a/vlib/v/ast/ast.v +++ b/vlib/v/ast/ast.v @@ -411,6 +411,7 @@ pub: pub struct AsCast { pub: + expr Expr typ table.Type } diff --git a/vlib/v/fmt/fmt.v b/vlib/v/fmt/fmt.v index 5c5a9bf7da..08e7e3a6be 100644 --- a/vlib/v/fmt/fmt.v +++ b/vlib/v/fmt/fmt.v @@ -308,6 +308,11 @@ fn (f mut Fmt) expr(node ast.Expr) { f.write(']') } } + ast.AsCast { + type_str := f.table.type_to_str(it.typ) + f.expr(it.expr) + f.write(' as $type_str') + } ast.AssignExpr { f.expr(it.left) f.write(' $it.op.str() ') diff --git a/vlib/v/fmt/tests/simple_expected.vv b/vlib/v/fmt/tests/simple_expected.vv index 260d92bcc0..c47dba4148 100644 --- a/vlib/v/fmt/tests/simple_expected.vv +++ b/vlib/v/fmt/tests/simple_expected.vv @@ -123,6 +123,10 @@ pub mut: pub_mut_field string } +struct Bar { + val int +} + const ( reserved_types = { 'i8': true @@ -188,3 +192,13 @@ fn fn_with_match_expr() { fn fn_variadic(arg int, args ...string) { println('Do nothing') } + +fn test_as() { + a := sum_expr() as Bar +} + +fn sum_expr() FooBar { + return Bar{ + val: 5 + } +} diff --git a/vlib/v/fmt/tests/simple_input.vv b/vlib/v/fmt/tests/simple_input.vv index ccd2a59cdb..0025efdd2f 100644 --- a/vlib/v/fmt/tests/simple_input.vv +++ b/vlib/v/fmt/tests/simple_input.vv @@ -125,6 +125,12 @@ struct Foo { pub_mut_field string } +struct Bar { + val int +} + +type FooBar = Foo | Bar + const ( reserved_types = { 'i8': true @@ -188,3 +194,11 @@ fn fn_with_match_expr() { fn fn_variadic(arg int, args... string) { println('Do nothing') } + +fn test_as() { + a := sum_expr() as Bar +} + +fn sum_expr() FooBar { + return Bar{ val: 5 } +} diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index 3acf8bff2c..93fa85b594 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -766,6 +766,7 @@ pub fn (p mut Parser) expr(precedence int) ast.Expr { p.next() typ = p.parse_type() node = ast.AsCast{ + expr: node typ: typ } }