Convert token.Pos to Position from *ast.File

347 views
Skip to first unread message

Archos

unread,
Dec 10, 2011, 3:51:18 PM12/10/11
to golang-nuts
The position of each elemnt is of type token.Pos, then how convert it
to token.Position?
Having in mind that parser.ParseFile returns *ast.File and it is
necessary to have token.File to convert from Pos to Position


/*
cat > test1.go << 'EOF'
package foo

var (
a = 10
b = "b"
)
EOF
*/

package main

import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"log"
)

func main() {
node, err := parser.ParseFile(token.NewFileSet(), "test1.go", nil, 0)
if err != nil {
log.Fatal(err)
}

for _, decl := range node.Decls {
if genDecl, ok := decl.(*ast.GenDecl); ok {
if genDecl.Tok == token.VAR {
for _, s := range genDecl.Specs {
vSpec := s.(*ast.ValueSpec)
for _, v := range vSpec.Names {
//fmt.Printf("%T", v.Pos()) // token.Pos
fmt.Printf("%d: %s\n", v.Pos(), v.Name)
}
}
}
}
}
}

Message has been deleted

Archos

unread,
Dec 10, 2011, 5:50:34 PM12/10/11
to golang-nuts
Yes, but as I said parser.ParseFile returns *ast.File not *ast.FileSet

On Dec 10, 9:20 pm, D Smithson <d_smith...@rocketmail.com> wrote:
> The FileSet Position method
> (http://golang.org/pkg/go/token/#FileSet.Position) converts a token Pos to
> a token Position.

Archos

unread,
Dec 10, 2011, 6:38:26 PM12/10/11
to golang-nuts
Well, it's solved so:

fs := token.NewFileSet()
node, err := parser.ParseFile(fs, "test1.go", nil, 0)

Then, it can be used "fs.Position(v.Pos())", although it would be
better if could be called Position() from *ast.File (node)

Reply all
Reply to author
Forward
Message has been deleted
0 new messages