From 9f9bfb98bdb9e97833f736cb69760e50ebd10c5b Mon Sep 17 00:00:00 2001 From: Tomoki Yamaguchi Date: Thu, 17 Aug 2023 03:08:32 +0900 Subject: [PATCH] fix: starting position of comment (#507) Fix Begin of Comment to point to the position of the opening slash. --- parser/lexer.go | 4 ++-- parser/parser_test.go | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/parser/lexer.go b/parser/lexer.go index 5b06c05f..f6544905 100644 --- a/parser/lexer.go +++ b/parser/lexer.go @@ -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() diff --git a/parser/parser_test.go b/parser/parser_test.go index 727d83c0..d94aa3e9 100644 --- a/parser/parser_test.go +++ b/parser/parser_test.go @@ -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 */") }) }