Skip to content

Commit

Permalink
parser: fix IndexExpr and ArrayInit precedence error (#298)
Browse files Browse the repository at this point in the history
  • Loading branch information
serkonda7 authored Jan 24, 2025
1 parent 25a5db5 commit 4807d74
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 3 deletions.
4 changes: 3 additions & 1 deletion lib/bait/lexer/lexer.bt
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub enum CommentMode {
pub struct Lexer {
mut comment_mode CommentMode
mut text string
mut insert_semi bool // Insert a semicolon on \n
mut insert_semi bool // Insert a semicolon on next \n
mut val string // Value of the current token

// Position tracking
Expand Down Expand Up @@ -344,9 +344,11 @@ fun (mut l Lexer) skip_whitespace() {
for l.pos < l.text.length {
c := l.text[l.pos]
if c == `\n` {
// \n as semicolon is handled in simple_token()
if l.insert_semi {
return
}

l.pos += 1
l.inc_line()
} else if c == ` ` or c == `\t` or c == `\r` {
Expand Down
5 changes: 3 additions & 2 deletions lib/bait/parser/expr.bt
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ fun (mut p Parser) expr(precedence token.Precedence) !ast.Expr {
node = p.dot_expr(node)!
} else if p.tok == .dotdot {
node = p.range_expr(node)!
} else if p.tok == .lsqr {
} else if p.tok == .lsqr and p.pos.line == p.prev_pos.line {
// If `[` is on next line, it's a different expr (see #297)
node = p.index_expr(node)!
} else if p.tok == .key_as {
node = p.as_cast(node)!
} else if p.tok.is_infix() {
node = p.infix_expr(node)!
} else {
panic('precedence not implemented: ${p.tok} at ${p.pos}')
return node
}
}
return node
Expand Down
2 changes: 2 additions & 0 deletions lib/bait/parser/parser.bt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ pub struct Parser {
mut tok token.Token
mut next_tok token.Token
mut val string
mut prev_pos token.Pos
mut pos token.Pos
mut pkg_name string
mut pkg_scope &context.Scope := 0 as any // Reference to scope of current package
Expand Down Expand Up @@ -267,6 +268,7 @@ fun (mut p Parser) next() {
}

p.val = p.lexer.val()
p.prev_pos = p.pos
p.pos = p.lexer.pos()
}

Expand Down
15 changes: 15 additions & 0 deletions tests/result/or_array_test.bt
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// SPDX-FileCopyrightText: 2023-present Lukas Neubert <[email protected]>
// SPDX-License-Identifier: MIT

fun call() ![]i32 {
return error("")
}

// See #297
fun test_default_empty_array() {
r := call() or {
println(err)
[]i32
}
assert r.length == 0
}

0 comments on commit 4807d74

Please sign in to comment.