1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

parser: support const x := 123, to make extracting locals as constants less annoying while prototyping

This commit is contained in:
Delyan Angelov 2023-08-03 15:39:17 +03:00
parent e3ade704cb
commit 598992b208
No known key found for this signature in database
GPG Key ID: 66886C0F12D595ED
5 changed files with 43 additions and 10 deletions

View File

@ -0,0 +1,19 @@
const a = 123
const b = 'abc'
const c = rune(123)
const d = u64(2 * c)
const f = func()
fn func() int {
return 42
}
dump(a)
dump(b)
dump(c)
dump(d)
dump(f)

View File

@ -0,0 +1,19 @@
const a := 123
const b := 'abc'
const c := rune(123)
const d := u64(2 * c)
const f := func()
fn func() int {
return 42
}
dump(a)
dump(b)
dump(c)
dump(d)
dump(f)

View File

@ -3713,10 +3713,13 @@ fn (mut p Parser) const_decl() ast.ConstDecl {
if p.tok.kind == .comma {
p.error_with_pos('const declaration do not support multiple assign yet', p.tok.pos())
}
// Allow for `const x := 123`, and for `const x = 123` too.
// Supporting `const x := 123` in addition to `const x = 123`, makes extracting local variables to constants much less annoying, while prototyping:
if p.tok.kind == .decl_assign {
p.error_with_pos('cannot use `:=` to declare a const, use `=` instead', p.tok.pos())
}
p.check(.decl_assign)
} else {
p.check(.assign)
}
end_comments << p.eat_comments()
if p.tok.kind == .key_fn {
p.error('const initializer fn literal is not a constant')

View File

@ -1,5 +0,0 @@
vlib/v/parser/tests/const_init_decl_assign_err.vv:2:4: error: cannot use `:=` to declare a const, use `=` instead
1 | const (
2 | a := 43
| ~~
3 | )

View File

@ -1,3 +0,0 @@
const (
a := 43
)