Source file
src/go/token/example_test.go
1
2
3
4
5 package token_test
6
7 import (
8 "fmt"
9 "go/ast"
10 "go/parser"
11 "go/token"
12 )
13
14 func Example_retrievePositionInfo() {
15 fset := token.NewFileSet()
16
17 const src = `package main
18
19 import "fmt"
20
21 import "go/token"
22
23 //line :1:5
24 type p = token.Pos
25
26 const bad = token.NoPos
27
28 //line fake.go:42:11
29 func ok(pos p) bool {
30 return pos != bad
31 }
32
33 /*line :7:9*/func main() {
34 fmt.Println(ok(bad) == bad.IsValid())
35 }
36 `
37
38 f, err := parser.ParseFile(fset, "main.go", src, 0)
39 if err != nil {
40 fmt.Println(err)
41 return
42 }
43
44
45 for _, decl := range f.Decls {
46
47
48
49
50 pos := decl.Pos()
51 relPosition := fset.Position(pos)
52 absPosition := fset.PositionFor(pos, false)
53
54
55 kind := "func"
56 if gen, ok := decl.(*ast.GenDecl); ok {
57 kind = gen.Tok.String()
58 }
59
60
61 fmtPosition := relPosition.String()
62 if relPosition != absPosition {
63 fmtPosition += "[" + absPosition.String() + "]"
64 }
65
66 fmt.Printf("%s: %s\n", fmtPosition, kind)
67 }
68
69
70
71
72
73
74
75
76
77 }
78
View as plain text