fix: starting position of comment (#507)

Fix Begin of Comment to point to the position of the opening slash.
This commit is contained in:
Tomoki Yamaguchi
2023-08-17 03:08:32 +09:00
committed by GitHub
parent 11288b7564
commit 9f9bfb98bd
2 changed files with 20 additions and 2 deletions

View File

@@ -237,7 +237,7 @@ func (p *parser) scan() (tkn token.Token, literal string, idx file.Idx) { //noli
case '/':
if p.mode&StoreComments != 0 {
literal := string(p.readSingleLineComment())
p.comments.AddComment(ast.NewComment(literal, p.idx))
p.comments.AddComment(ast.NewComment(literal, idx))
continue
}
p.skipSingleLineComment()
@@ -245,7 +245,7 @@ func (p *parser) scan() (tkn token.Token, literal string, idx file.Idx) { //noli
case '*':
if p.mode&StoreComments != 0 {
literal = string(p.readMultiLineComment())
p.comments.AddComment(ast.NewComment(literal, p.idx))
p.comments.AddComment(ast.NewComment(literal, idx))
continue
}
p.skipMultiLineComment()

View File

@@ -1186,6 +1186,24 @@ func TestPosition(t *testing.T) {
node = program.Body[0].(*ast.DoWhileStatement)
is(node.Idx0(), 1)
is(parser.slice(node.Idx0(), node.Idx1()), "do { i++; } while (i < 10 )")
parser = newParser("", "(function() { // single-line comment\n })", 1, nil)
parser.mode |= StoreComments
program, err = parser.parse()
is(err, nil)
block = program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.FunctionLiteral).Body.(*ast.BlockStatement)
comment := parser.comments.CommentMap[block][0]
is(comment.Begin, 15)
is(parser.slice(comment.Begin, file.Idx(int(comment.Begin)+len(comment.Text)+2)), "// single-line comment")
parser = newParser("", "(function() { /* multi-line comment */ })", 1, nil)
parser.mode |= StoreComments
program, err = parser.parse()
is(err, nil)
block = program.Body[0].(*ast.ExpressionStatement).Expression.(*ast.FunctionLiteral).Body.(*ast.BlockStatement)
comment = parser.comments.CommentMap[block][0]
is(comment.Begin, 15)
is(parser.slice(comment.Begin, file.Idx(int(comment.Begin)+len(comment.Text)+4)), "/* multi-line comment */")
})
}