ast.go 1017 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package ast
  2. import (
  3. "fmt"
  4. "go/ast"
  5. "go/token"
  6. )
  7. // 增加 import 方法
  8. func AddImport(astNode ast.Node, imp string) {
  9. impStr := fmt.Sprintf("\"%s\"", imp)
  10. ast.Inspect(astNode, func(node ast.Node) bool {
  11. if genDecl, ok := node.(*ast.GenDecl); ok {
  12. if genDecl.Tok == token.IMPORT {
  13. for i := range genDecl.Specs {
  14. if impNode, ok := genDecl.Specs[i].(*ast.ImportSpec); ok {
  15. if impNode.Path.Value == impStr {
  16. return false
  17. }
  18. }
  19. }
  20. genDecl.Specs = append(genDecl.Specs, &ast.ImportSpec{
  21. Path: &ast.BasicLit{
  22. Kind: token.STRING,
  23. Value: impStr,
  24. },
  25. })
  26. }
  27. }
  28. return true
  29. })
  30. }
  31. // 查询特定function方法
  32. func FindFunction(astNode ast.Node, FunctionName string) *ast.FuncDecl {
  33. var funcDeclP *ast.FuncDecl
  34. ast.Inspect(astNode, func(node ast.Node) bool {
  35. if funcDecl, ok := node.(*ast.FuncDecl); ok {
  36. if funcDecl.Name.String() == FunctionName {
  37. funcDeclP = funcDecl
  38. return false
  39. }
  40. }
  41. return true
  42. })
  43. return funcDeclP
  44. }