Map tokens to exact source positions
Map tokens to exact source positions
A tooling diagnostic needs a location in the original file, not just a token kind. A token.FileSet gives each file a distinct position range; token.Pos is meaningful in that set, and File.Offset converts it to a byte offset within that file. Unlike the compiler overview, here we extract an exact source span for a tool. Save this program as main.go and run go run main.go locally.
package main
import ( "fmt" "go/ast" "go/parser" "go/token")
func main() { src := []byte(`package pvar café = 7`) fs := token.NewFileSet() f, err := parser.ParseFile(fs, "p.go", src, 0) if err != nil { panic(err) } ast.Inspect(f, func(n ast.Node) bool { if id, ok := n.(*ast.Ident); ok && id.Name == "café" { file := fs.File(id.Pos()) p := fs.Position(id.Pos()) fmt.Printf("%d:%d %s %d bytes\n", p.Line, p.Column, src[file.Offset(id.Pos()):file.Offset(id.End())], file.Offset(id.End())-file.Offset(id.Pos())) } return true })}Positions are one-based for lines and byte columns; the slice uses zero-based byte offsets with an exclusive end. The accented identifier occupies five UTF-8 bytes but four Unicode code points. Do not slice source using a raw token.Pos or assume byte columns equal visual/editor columns. PositionFor with adjusted=false ignores line directives when you need physical file locations.
Expected output:
2:5 café 5 bytesKeep scanner errors separate from tokens
package main
import ( "fmt" "go/scanner" "go/token")
func main() { src := []byte("x @ y") fs := token.NewFileSet() f := fs.AddFile("p.go", -1, len(src)) var s scanner.Scanner s.Init(f, src, func(p token.Position, msg string) { fmt.Println(p.Line, p.Column) }, 0) for { _, tok, _ := s.Scan() if tok == token.EOF { break } } fmt.Println(s.ErrorCount)}A scanner can continue after an illegal character. A tool must track errors instead of assuming reaching EOF means success. For partial trees, report diagnostics without applying automatic fixes until the relevant syntax is understood.
Expected output:
1 31Try it locally
Parse package p; var score = 42 and print the exact source span of the integer literal and its byte length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Developer tooling 01: Map tokens to exact source positions
Check the lesson objective before moving on.
How do you obtain a byte offset from a token.Pos?
Why can a diagnostic column differ from an editor column?