How to compute the offset from column and line number ? – Go

huangapple go评论109阅读模式
英文:

How to compute the offset from column and line number ? - Go

问题

我需要使用列号和行号作为参考来计算源代码文件中的偏移量(例如source.go:23:42)。如何计算偏移量?我正在使用一些Go工具(oracleasttoken)来分析源代码。

英文:

I need to compute the offset in a source code file using a column and line number as reference (e.g. source.go:23:42). How can I compute the offset ? I'm using it to analyse the source code with some go tools(oracle, ast and token).

答案1

得分: 2

由于行宽不固定,无法快速知道偏移量。您需要逐个字符遍历文件内容并计算偏移量。可以使用以下类似的代码:

  1. func findOffset(fileText string, line, column int) int {
  2. // 记录当前行和列的位置
  3. currentCol := 1
  4. currentLine := 1
  5. for offset, ch := range fileText {
  6. // 检查是否找到了目标位置
  7. if currentLine == line && currentCol == column {
  8. return offset
  9. }
  10. // 换行符 - 增加行计数器并重置列
  11. if ch == '\n' {
  12. currentLine++
  13. currentCol = 1
  14. } else {
  15. currentCol++
  16. }
  17. }
  18. return -1 // 未找到
  19. }
  20. // 这是我们的源代码示例
  21. var sampleText = `package main
  22. var foo = "hello"
  23. var bar = "world"
  24. `
  25. func main() {
  26. fmt.Println(findOffset(sampleText, 1, 1)) // 输出 0
  27. fmt.Println(findOffset(sampleText, 3, 5)) // 输出 18
  28. }

Playground链接:http://play.golang.org/p/fWb9N9r9pi

英文:

Since line width isn't fixed, there's no quick way of knowing that. you need to traverse the file's content character by character and count the offset. something like:

  1. func findOffset(fileText string, line, column int) int {
  2. // we count our current line and column position
  3. currentCol := 1
  4. currentLine := 1
  5. for offset,ch := range fileText {
  6. // see if we found where we wanted to go to
  7. if currentLine == line && currentCol == column {
  8. return offset
  9. }
  10. // line break - increment the line counter and reset the column
  11. if ch == '\n' {
  12. currentLine++
  13. currentCol = 1
  14. } else {
  15. currentCol++
  16. }
  17. }
  18. return -1; //not found
  19. }
  20. // this here is our source code for example
  21. var sampleText = `package main
  22. var foo = "hello"
  23. var bar ="world"
  24. `
  25. func main() {
  26. fmt.Println(findOffset(sampleText, 1, 1)) //prints 0
  27. fmt.Println(findOffset(sampleText, 3, 5)) //prints 18
  28. }

Playground link: http://play.golang.org/p/fWb9N9r9pi

huangapple
  • 本文由 发表于 2015年1月18日 18:02:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/28008566.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定