Skip to content

Instantly share code, notes, and snippets.

View campoy's full-sized avatar

Francesc Campoy campoy

View GitHub Profile
package main
import (
"go/parser"
"go/printer"
"go/token"
"log"
"os"
)
type Visitor interface {
Visit(node Node) (w Visitor)
}
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"log"
)
type visitor int
func (v visitor) Visit(n ast.Node) ast.Visitor {
if n == nil {
return nil
}
fmt.Printf("%s%T\n", strings.Repeat("\t", int(v)), n)
return v + 1
}
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"log"
"os"
"strings"
type visitor struct {
locals map[string]int
}
func (v visitor) Visit(n ast.Node) ast.Visitor {
if n == nil {
return nil
}
switch d := n.(type) {
case *ast.AssignStmt:
func (v visitor) local(n ast.Node) {
ident, ok := n.(*ast.Ident)
if !ok {
return
}
if ident.Name == "_" || ident.Name == "" {
return
}
if ident.Obj != nil && ident.Obj.Pos() == ident.Pos() {
v.locals[ident.Name]++
func (v visitor) localList(fs []*ast.Field) {
for _, f := range fs {
for _, name := range f.Names {
v.local(name)
}
}
}
case *ast.AssignStmt:
if d.Tok != token.DEFINE {
return v
}
for _, name := range d.Lhs {
v.local(name)
}
case *ast.RangeStmt:
v.local(d.Key)
v.local(d.Value)
type visitor struct {
pkgDecls map[*ast.GenDecl]bool
globals map[string]int
locals map[string]int
}
func newVisitor(f *ast.File) visitor {
decls := make(map[*ast.GenDecl]bool)
for _, decl := range f.Decls {
if d, ok := decl.(*ast.GenDecl); ok {