From c4b7d7cab3050454a1c10a3ca9591d169be1c321 Mon Sep 17 00:00:00 2001 From: Alexander Medvednikov Date: Fri, 17 Apr 2020 19:24:07 +0200 Subject: [PATCH] match: shadow variable instead of `it` --- vlib/v/parser/if.v | 21 ++++++++++++++++++++- vlib/v/tests/sum_type_test.v | 4 ++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/vlib/v/parser/if.v b/vlib/v/parser/if.v index 9b01b53b8d..4bf0db56b0 100644 --- a/vlib/v/parser/if.v +++ b/vlib/v/parser/if.v @@ -124,6 +124,26 @@ fn (var p Parser) match_expr() ast.MatchExpr { p.parse_type() } is_sum_type = true + // Make sure a variable used for the sum type match + var var_name := '' + match cond { + ast.Ident { + var_name = it.name + } + else { + // p.error('only variables can be used in sum types matches') + } + } + if var_name != '' { + // Register a shadow variable with the actual type + // (this replaces the old `it`) + // TODO doesn't work right now + p.scope.register(var_name, ast.Var{ + name: var_name + typ: table.type_to_ptr(typ) + }) + // println(var_name) + } } else { // Expression match for { @@ -172,4 +192,3 @@ fn (var p Parser) match_expr() ast.MatchExpr { is_mut: is_mut } } - diff --git a/vlib/v/tests/sum_type_test.v b/vlib/v/tests/sum_type_test.v index ade2a62eb7..e4230a3172 100644 --- a/vlib/v/tests/sum_type_test.v +++ b/vlib/v/tests/sum_type_test.v @@ -16,7 +16,7 @@ fn handle(e Expr) string { match e { IntegerLiteral { assert it.val == '12' - // assert e.val == '12' + // assert e.val == '12' // TODO return 'int' } IfExpr { @@ -31,5 +31,5 @@ fn test_expr() { val: '12' } assert handle(expr) == 'int' - // assert expr is IntegerLiteral + // assert expr is IntegerLiteral // TODO }