When I parse go source file with the parser
package, the package xxx
statement was considered as a normal *ast.Ident
. Is there any way to distinguish it from other declarations? Or gracefully ignore the package statement while parsing?
func walk(node ast.Node) bool {
switch n := node.(type) {
case *ast.File:
return true
case *ast.Ident:
// I want to check whether it is a package statement
case *ast.GenDecl:
return true
case *ast.TypeSpec:
return true
case *ast.StructType:
return true
case *ast.FieldList:
return true
case *ast.Field:
if len(n.Names) > 0 {
fmt.Println(n.Names[0].String())
}
default:
fmt.Printf("%T
", node)
}
return false
}
func parseFile(filename string) error {
fs := token.NewFileSet()
f, err := parser.ParseFile(fs, filename, nil, parser.ParseComments)
if err != nil {
return err
}
ast.Inspect(f, walk)
return nil
}