Skip to content

Commit

Permalink
parser: allow for variable name using keyword 'type' (vlang#22512)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 authored Oct 14, 2024
1 parent 5c65e58 commit 7220f75
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 6 deletions.
14 changes: 10 additions & 4 deletions vlib/v/parser/expr.v
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ fn (mut p Parser) check_expr(precedence int) !ast.Expr {
if p.peek_tok.kind in [.lpar, .lsbr] && p.peek_tok.is_next_to(p.tok) {
node = p.call_expr(p.language, p.mod)
} else {
ident := p.ident(ast.Language.v)
ident := p.ident(.v)
node = ident
if p.peek_tok.kind != .assign && (p.inside_if_cond || p.inside_match) {
p.mark_var_as_used(ident.name)
Expand Down Expand Up @@ -519,8 +519,14 @@ fn (mut p Parser) check_expr(precedence int) !ast.Expr {
p.next()
return p.struct_init('', .anon, false)
}
}
if p.tok.kind != .eof && !(p.tok.kind == .rsbr && p.inside_asm) {
} else if p.tok.kind == .key_type {
// variable name: type
ident := p.ident(.v)
node = ident
p.mark_var_as_used(ident.name)
p.add_defer_var(ident)
p.is_stmt_ident = is_stmt_ident
} else if p.tok.kind != .eof && !(p.tok.kind == .rsbr && p.inside_asm) {
// eof should be handled where it happens
return error('none')
// return p.unexpected(prepend_msg: 'invalid expression: ')
Expand Down Expand Up @@ -938,7 +944,7 @@ fn (mut p Parser) lambda_expr() ?ast.LambdaExpr {
if p.tok.kind == .eof {
break
}
ident := p.ident(ast.Language.v)
ident := p.ident(.v)
if p.scope.known_var(ident.name) {
p.error_with_pos('redefinition of parameter `${ident.name}`', ident.pos)
}
Expand Down
4 changes: 2 additions & 2 deletions vlib/v/parser/parser.v
Original file line number Diff line number Diff line change
Expand Up @@ -2326,7 +2326,7 @@ fn (mut p Parser) ident(language ast.Language) ast.Ident {
if is_volatile {
p.next()
}
if p.tok.kind != .name {
if p.tok.kind !in [.name, .key_type] {
if is_mut || is_static || is_volatile {
p.error_with_pos('the `${modifier_kind}` keyword is invalid here', mut_pos)
} else {
Expand Down Expand Up @@ -2621,7 +2621,7 @@ fn (mut p Parser) name_expr() ast.Expr {
is_known_var := p.scope.known_var(p.tok.lit)
if is_known_var {
p.mark_var_as_used(p.tok.lit)
return p.ident(ast.Language.v)
return p.ident(.v)
} else {
type_pos := p.tok.pos()
typ := p.parse_type()
Expand Down
22 changes: 22 additions & 0 deletions vlib/v/tests/var_name_using_type_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
fn info(type int) int {
return type
}

fn print_info() {
for type in [1, 2, 3] {
println(type)
}
}

fn test_var_name_using_type() {
ret := info(22)
println(ret)
assert ret == 22

type := 33
println(type)
assert type == 33

print_info()
assert true
}

0 comments on commit 7220f75

Please sign in to comment.