Skip to content

Commit

Permalink
fix: indexes of do-while statement
Browse files Browse the repository at this point in the history
Set Idx0 of DoWhileStatement and fix Idx1 to points to the next character after the right parenthesis.
  • Loading branch information
tyamagu2 committed Jul 24, 2023
1 parent ddfec7d commit a9d7d31
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 7 deletions.
9 changes: 5 additions & 4 deletions ast/node.go
Original file line number Diff line number Diff line change
Expand Up @@ -619,9 +619,10 @@ func (*DebuggerStatement) statement() {}

// DoWhileStatement represents a do while statement.
type DoWhileStatement struct {
Do file.Idx
Test Expression
Body Statement
Do file.Idx
Test Expression
Body Statement
RightParenthesis file.Idx
}

// Idx0 implements Node.
Expand All @@ -631,7 +632,7 @@ func (dws *DoWhileStatement) Idx0() file.Idx {

// Idx1 implements Node.
func (dws *DoWhileStatement) Idx1() file.Idx {
return dws.Test.Idx1()
return dws.RightParenthesis + 1
}

// expression implements Statement.
Expand Down
7 changes: 7 additions & 0 deletions parser/parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1178,6 +1178,13 @@ func TestPosition(t *testing.T) {
node = program.Body[0].(*ast.WhileStatement)
is(node.Idx0(), 1)
is(parser.slice(node.Idx0(), node.Idx1()), "while (i < 10) { i++; }")

parser = newParser("", "do { i++; } while (i < 10 )", 1, nil)
program, err = parser.parse()
is(err, nil)
node = program.Body[0].(*ast.DoWhileStatement)
is(node.Idx0(), 1)
is(parser.slice(node.Idx0(), node.Idx1()), "do { i++; } while (i < 10 )")
})
}

Expand Down
6 changes: 3 additions & 3 deletions parser/statement.go
Original file line number Diff line number Diff line change
Expand Up @@ -661,13 +661,13 @@ func (p *parser) parseDoWhileStatement() ast.Statement {
if p.mode&StoreComments != 0 {
comments = p.comments.FetchAll()
}
p.expect(token.DO)
idx := p.expect(token.DO)
var doComments []*ast.Comment
if p.mode&StoreComments != 0 {
doComments = p.comments.FetchAll()
}

node := &ast.DoWhileStatement{}
node := &ast.DoWhileStatement{Do: idx}
if p.token == token.LEFT_BRACE {
node.Body = p.parseBlockStatement()
} else {
Expand All @@ -681,7 +681,7 @@ func (p *parser) parseDoWhileStatement() ast.Statement {
}
p.expect(token.LEFT_PARENTHESIS)
node.Test = p.parseExpression()
p.expect(token.RIGHT_PARENTHESIS)
node.RightParenthesis = p.expect(token.RIGHT_PARENTHESIS)

p.implicitSemicolon = true
p.optionalSemicolon()
Expand Down

0 comments on commit a9d7d31

Please sign in to comment.