forked from KurokuLabs/margo
/
mutex-snippet.go
62 lines (56 loc) · 1.22 KB
/
mutex-snippet.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
package snippets
import (
"go/ast"
"margo.sh/golang/cursor"
"margo.sh/golang/goutil"
"margo.sh/mg"
"strings"
)
func MutexSnippet(cx *cursor.CurCtx) []mg.Completion {
x, ok := cx.Node.(*ast.SelectorExpr)
if !ok {
return nil
}
sel, _ := cx.Print(x)
sel = strings.TrimRightFunc(sel, func(r rune) bool { return r != '.' })
if sel == "" {
return nil
}
snips := func(lock, unlock string) []mg.Completion {
return []mg.Completion{
{
Query: lock + `; defer ` + unlock,
Src: goutil.DedentCompletion(`
` + lock + `()
defer ` + sel + unlock + `()
$0
`),
Tag: mg.SnippetTag,
},
{
Query: lock + `; ...; ` + unlock,
Src: goutil.DedentCompletion(`
` + lock + `()
$0
` + sel + unlock + `()
`),
Tag: mg.SnippetTag,
},
}
}
// as a temporary hack, until we have typechecking,
// we'll rely on the gocode reducer to tell us if this is a lock
cx.Ctx.Defer(func(mx *mg.Ctx) *mg.State {
cl := []mg.Completion{}
for _, c := range mx.State.Completions {
switch c.Query {
case "Lock":
cl = append(cl, snips("Lock", "Unlock")...)
case "RLock":
cl = append(cl, snips("RLock", "RUnlock")...)
}
}
return mx.AddCompletions(cl...)
})
return nil
}