-
Notifications
You must be signed in to change notification settings - Fork 0
/
finders.go
79 lines (70 loc) · 2 KB
/
finders.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright 2023 The ppacer Authors.
// Licensed under the Apache License, Version 2.0.
// See LICENSE file in the project root for full license information.
package meta
import (
"bytes"
"errors"
"go/ast"
"go/printer"
"reflect"
)
var ErrMethodNotFound = errors.New("method not found in ASTs")
// MethodBodySource finds given method for given type in the AST and return
// it's body AST and source code as string. If given type or method does not
// exist in given ASTs map, then non nil error would be returned.
func MethodBodySource(
astMap map[string]PackageASTs, typeName, methodName string,
) (*ast.BlockStmt, string, error) {
for pkg := range astMap {
for _, astFile := range astMap[pkg].FileToASTs {
funcDecl := findMethodInAST(astFile, typeName, methodName)
if funcDecl == nil {
continue
}
var buf bytes.Buffer
err := printer.Fprint(&buf, astMap[pkg].Fset, funcDecl.Body)
if err != nil {
return nil, "", err
}
return funcDecl.Body, buf.String(), nil
}
}
return nil, "", ErrMethodNotFound
}
func findMethodInAST(astFile *ast.File, typeName, methodName string) *ast.FuncDecl {
for _, decl := range astFile.Decls {
funcDecl, isFunc := decl.(*ast.FuncDecl)
if !isFunc {
continue
}
if funcDecl.Recv == nil || len(funcDecl.Recv.List) != 1 || funcDecl.Name.Name != methodName {
continue
}
ident, isIdent := funcDecl.Recv.List[0].Type.(*ast.Ident)
if isIdent && ident.Name == typeName {
return funcDecl
}
// Check for *T receivers
starExpr, isStar := funcDecl.Recv.List[0].Type.(*ast.StarExpr)
if isStar {
ident, isIdent := starExpr.X.(*ast.Ident)
if isIdent && ident.Name == typeName {
return funcDecl
}
}
}
return nil
}
// TypeName returns string with type name of given object. For pointers (*T)
// underlying type name is returned.
func TypeName(t any) string {
var typeName string
tType := reflect.TypeOf(t)
if tType.Kind() == reflect.Ptr {
typeName = tType.Elem().Name()
} else {
typeName = tType.Name()
}
return typeName
}