英文:
What kind of encoding does posFlag requires?
问题
你可以使用正则表达式来提取 /pathto/file.go:40:32
中的行号和列号,然后将其拼接到 posFlag
参数中。以下是一个示例代码:
import (
"fmt"
"regexp"
)
func main() {
position := "/pathto/file.go:40:32"
re := regexp.MustCompile(`:(\d+):(\d+)`)
matches := re.FindStringSubmatch(position)
if len(matches) == 3 {
line := matches[1]
column := matches[2]
posFlag := fmt.Sprintf("%s:#%s", position[:len(position)-len(matches[0])], line)
fmt.Println(posFlag)
}
}
这段代码使用正则表达式 :(\d+):(\d+)
来匹配行号和列号。然后,通过 fmt.Sprintf
将路径和行号拼接成 posFlag
参数的格式 /pathto/file.go:#40
。你可以根据自己的需求进行修改和调整。
英文:
How can I encode the position of the form /pathto/file.go:40:32
which is returned by token.Position.String()
to a posFlag
param required by ParseQueryPos
which looks like /pathto/file.go:#550
.
Why?
I'm using the Oracle
tool to do some static analysis. I need to run Oracle.Query
which requires a param of type *QueryPos
. The only way to get *QueryPos
is using ParseQueryPos
.
答案1
得分: 1
tools/pos.go
中的代码被ParseQueryPos调用,代码注释如下:
// parsePosFlag解析形如"file:pos"或"file:start,end"的字符串,
// 其中pos、start、end匹配#%d并表示字节偏移量,返回其组成部分。
如果你真的需要将line:column
字符串转换为字节偏移量,你需要查看文件内容并计算到达该行列的字节数(包括换行符)。但由于你正在使用token.Position
,看起来你可以从token.Position.Offset
中获取所需的信息。
英文:
The source to tools/pos.go
called by ParseQueryPos says
// parsePosFlag parses a string of the form "file:pos" or
// file:start,end" where pos, start, end match #%d and represent byte
// offsets, and returns its components.
If you really had to convert from line:column
strings, you'd look at the file contents and count up bytes (including newlines) leading to that line:column. But since you're working with a token.Position
, it looks like you can get what you need from token.Position.Offset
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论