/
profiler.go
109 lines (93 loc) · 2.46 KB
/
profiler.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package profiler
import (
"fmt"
"regexp"
"github.com/luthersystems/elps/lisp"
"github.com/luthersystems/elps/parser/token"
)
// profiler is a minimal lisp.Profiler
type profiler struct {
runtime *lisp.Runtime
enabled bool
skipFilter SkipFilter
funLabeler FunLabeler
}
var _ lisp.Profiler = &profiler{}
func (p *profiler) IsEnabled() bool {
return p.enabled
}
type Option func(*profiler)
func (p *profiler) applyConfigs(opts ...Option) {
for _, opt := range opts {
opt(p)
}
}
func (p *profiler) Enable() error {
if p.enabled {
return fmt.Errorf("profiler already enabled")
}
p.enabled = true
return nil
}
func (p *profiler) Start(fun *lisp.LVal) func() {
return func() {}
}
// defaultFunName constructs a pretty canonical name using the function name.
func defaultFunName(runtime *lisp.Runtime, fun *lisp.LVal) string {
if fun.Type != lisp.LFun {
return ""
}
funData := fun.FunData()
if funData == nil {
return ""
}
name := ""
if env := fun.Env(); env != nil {
name = env.GetFunName(fun)
}
if name == "" {
name = getFunNameFromFID(runtime, funData.FID)
}
return name
}
// prettyFunName returns a pretty name and original name for a fun. If there is
// no pretty name, then the pretty name is the original name. The pretty name
// includes the package prefix, while the original name does not.
func (p *profiler) prettyFunName(fun *lisp.LVal) (string, string) {
origLabel := defaultFunName(p.runtime, fun)
if origLabel == "" {
return "", ""
}
prettyLabel := origLabel
if p.funLabeler != nil {
prettyLabel = p.funLabeler(p.runtime, fun)
}
if prettyLabel == "" {
prettyLabel = origLabel
}
return prettyLabel, origLabel
}
// skipTrace is a helper function to decide whether to skip tracing.
func (p *profiler) skipTrace(v *lisp.LVal) bool {
return !p.enabled || defaultSkipFilter(v) || p.skipFilter != nil && p.skipFilter(v)
}
var builtinRegex = regexp.MustCompile("\\<(?:builtin|special)-[a-z]+ \\`\\`(.*)\\'\\'\\>")
// Gets a canonical version of the function name suitable for human viewing.
func getFunNameFromFID(rt *lisp.Runtime, in string) string {
// but sometimes something doesn't match - so we'll try to regexp it out
if !builtinRegex.MatchString(in) {
return in
}
return builtinRegex.FindStringSubmatch(in)[1]
}
func getSourceLoc(fun *lisp.LVal) *token.Location {
if len(fun.Cells) > 0 {
if cell := fun.Cells[0]; cell.Source != nil {
return cell.Source
}
}
if fun.Source != nil {
return fun.Source
}
return nil
}