-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfuncRegistry.go
71 lines (63 loc) · 1.63 KB
/
funcRegistry.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
package main
import (
"go/ast"
"log"
"golang.org/x/tools/go/packages"
)
type (
FuncProps struct{ DeterministicReturn bool }
FuncRegistry map[string]FuncProps
)
func analyzeFunc(pkg *packages.Package, funcDecl *ast.FuncDecl) FuncProps {
staticReturns := 0
dynamicReturns := 0
ast.Inspect(funcDecl, func(node ast.Node) bool {
returnStmt, ok := node.(*ast.ReturnStmt)
if !ok {
return true
}
static, dynamic := 0, 0
for _, result := range returnStmt.Results {
typeAndValue, ok := pkg.TypesInfo.Types[result]
if ok && (typeAndValue.Value != nil || typeAndValue.IsNil()) {
static++
} else {
dynamic++
}
}
if dynamic == 0 {
staticReturns++
} else {
dynamicReturns++
}
return true
})
return FuncProps{DeterministicReturn: staticReturns <= 1 && dynamicReturns == 0}
}
func (r *FuncRegistry) fillFuncRegistryFromPkg(pkg *packages.Package, visitedPkgs map[string]struct{}) {
if _, ok := visitedPkgs[pkg.ID]; ok {
return
}
visitedPkgs[pkg.ID] = struct{}{}
for _, file := range pkg.Syntax {
ast.Inspect(file, func(node ast.Node) bool {
if funcDecl, ok := node.(*ast.FuncDecl); ok {
(*r)[funcDecl.Name.Name] = analyzeFunc(pkg, funcDecl)
return false
}
return true
})
}
for _, importPkg := range pkg.Imports {
r.fillFuncRegistryFromPkg(importPkg, visitedPkgs)
}
}
func CreateFuncRegistry(pkgs []*packages.Package) FuncRegistry {
visitedPkgs := make(map[string]struct{})
funcRegistry := make(FuncRegistry)
for _, pkg := range pkgs {
funcRegistry.fillFuncRegistryFromPkg(pkg, visitedPkgs)
}
log.Printf("built func registry: %v entries", len(funcRegistry))
return funcRegistry
}