github.com/jmigpin/editor@v1.6.0/util/astut/util.go (about) 1 package astut 2 3 import ( 4 "bytes" 5 "fmt" 6 "go/ast" 7 "go/printer" 8 "go/token" 9 ) 10 11 func NodeFilename(fset *token.FileSet, node ast.Node) (string, error) { 12 f := fset.File(node.Pos()) 13 if f == nil { 14 return "", fmt.Errorf("not found") 15 } 16 return f.Name(), nil 17 } 18 19 //---------- 20 21 // print ast notes 22 // TODO: without tabwidth set, it won't output the source correctly 23 // Fail: has struct fields without spaces "field int"->"fieldint" 24 //cfg := &printer.Config{Mode: printer.SourcePos | printer.TabIndent} 25 // Fail: has stmts split with comments in the middle 26 //cfg := &printer.Config{Mode: printer.SourcePos | printer.TabIndent | printer.UseSpaces} 27 // debug 28 //cfg := &printer.Config{Tabwidth: 4} 29 //cfg := &printer.Config{Mode: printer.SourcePos, Tabwidth: 4} 30 31 func PrintNode(fset *token.FileSet, n ast.Node) { 32 fmt.Println(SprintNode(fset, n)) 33 } 34 func SprintNode(fset *token.FileSet, n ast.Node) string { 35 s, err := SprintNode2(fset, n) 36 if err != nil { 37 return fmt.Sprintf("<sprintnodeerr:%v>", err) 38 } 39 return s 40 } 41 func SprintNode2(fset *token.FileSet, n ast.Node) (string, error) { 42 buf := &bytes.Buffer{} 43 cfg := &printer.Config{Mode: printer.RawFormat} 44 if err := cfg.Fprint(buf, fset, n); err != nil { 45 return "", err 46 } 47 return string(buf.Bytes()), nil 48 }