parser: fix inline array's element access (#14253)

yuyi 2022-05-02 21:16:32 +08:00 committed by Jef Roosens
parent 6468bcd0a6
commit 21555fb03a
Signed by: Jef Roosens
GPG Key ID: B75D4F293C7052DB
3 changed files with 35 additions and 1 deletions

View File

@ -1557,3 +1557,15 @@ fn test_generic_mutable_arrays() {
mut arr := [1, 2, 3]
assert example(mut arr) == [1, 2, 3]
}
struct Ok {}
fn test_inline_array_element_access() {
println([Ok{}][0])
a1 := [Ok{}][0]
assert a1 == Ok{}
println([1][0])
a2 := [1][0]
assert a2 == 1
}

View File

@ -65,7 +65,8 @@ fn (mut p Parser) array_init() ast.ArrayInit {
}
last_pos = p.tok.pos()
p.check(.rsbr)
if exprs.len == 1 && p.tok.kind in [.name, .amp, .lsbr] && p.tok.line_nr == line_nr {
if exprs.len == 1 && p.tok.line_nr == line_nr
&& (p.tok.kind in [.name, .amp] || (p.tok.kind == .lsbr && p.is_array_type())) {
// [100]u8
elem_type = p.parse_type()
if p.table.sym(elem_type).name == 'byte' {

View File

@ -480,6 +480,27 @@ pub fn (p &Parser) peek_token_after_var_list() token.Token {
return tok
}
fn (p &Parser) is_array_type() bool {
mut i := 1
mut tok := p.tok
line_nr := p.tok.line_nr
for {
tok = p.peek_token(i)
if tok.line_nr != line_nr {
return false
}
if tok.kind in [.name, .amp] {
return true
}
i++
if tok.kind == .lsbr || tok.kind != .rsbr {
continue
}
}
return false
}
pub fn (mut p Parser) open_scope() {
p.scope = &ast.Scope{
parent: p.scope