This repository has been archived by the owner on Aug 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
main.go
198 lines (171 loc) · 6.96 KB
/
main.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
package main // import "github.com/saibing/bingo"
import (
"context"
"flag"
"fmt"
"io"
"log"
"net"
"net/http"
"os"
"runtime/debug"
"strings"
"time"
"github.com/sourcegraph/jsonrpc2"
"github.com/saibing/bingo/langserver"
_ "net/http/pprof"
)
var (
mode = flag.String("mode", "stdio", "communication mode (stdio|tcp)")
addr = flag.String("addr", ":4389", "server listen address (tcp)")
trace = flag.Bool("trace", false, "print all requests and responses")
logfile = flag.String("logfile", "", "also log to this file (in addition to stderr)")
printVersion = flag.Bool("version", false, "print version and exit")
freeosmemory = flag.Int("freeosmemory", 0, "the interval time that aggressively free memory back to the OS, unit is second, default value is 0, means no free memroy back to the OS")
pprof = flag.String("pprof", "", "start a pprof http server (https://golang.org/pkg/net/http/pprof/)")
// Default Config, can be overridden by InitializationOptions
diagnosticsStyle = flag.String("diagnostics-style", "instant", "diagnostics style: none, instant, onsave. Can be overridden by InitializationOptions.")
disableFuncSnippet = flag.Bool("disable-func-snippet", false, "disable argument snippets on func completion. Can be overridden by InitializationOptions.")
globalCacheStyle = flag.String("cache-style", "always", "set global cache style: none, on-demand, always. Can be overridden by InitializationOptions.")
formatStyle = flag.String("format-style", "goimports", "which format style is used to format documents. Supported: gofmt and goimports. Can be overridden by InitializationOptions.")
goimportsPrefix = flag.String("goimports-prefix", "", "set '--local' flag for the goimports invocation. Can be overridden by InitializationOptions.")
enhanceSignatureHelp = flag.Bool("enhance-signature-help", false, "enhance signature help with return result. Can be overridden by InitializationOptions.")
buildTags = flag.String("build-tags", "", "build tags, separated by spaces.")
// Compatible with sourcegraph/go-langserver, ensuring that ide-go can run, but no actual effect
// https://github.com/saibing/bingo/issues/163
gocodecompletion = flag.Bool("gocodecompletion", false, "enable completion. no actual effect, just for compatible with ide-go")
diagnostics = flag.Bool("diagnostics", false, "enable diagnostics. no actual effect, just for compatible with ide-go")
funcSnippetEnabled = flag.Bool("func-snippet-enabled", true, "enable argument snippets on func completion. no actual effect, just for compatible with ide-go")
formatTool = flag.String("format-tool", "goimports", "which tool is used to format documents. no actual effect, just for compatible with ide-go")
)
// version is the version field we report back. If you are releasing a new version:
// 1. Create commit without -dev suffix.
// 2. Create commit with version incremented and -dev suffix
// 3. Push to master
// 4. Tag the commit created in (1) with the value of the version string
const version = "v2-dev"
func main() {
flag.Parse()
log.SetFlags(0)
// Start pprof server, if desired.
if *pprof != "" {
go func() {
log.Println(http.ListenAndServe(*pprof, nil))
}()
}
if *freeosmemory > 0 {
go freeOSMemory()
}
cfg := langserver.NewDefaultConfig()
cfg.DisableFuncSnippet = *disableFuncSnippet
cfg.DiagnosticsStyle = *diagnosticsStyle
cfg.GlobalCacheStyle = *globalCacheStyle
cfg.FormatStyle = *formatStyle
cfg.GoimportsLocalPrefix = *goimportsPrefix
cfg.EnhanceSignatureHelp = *enhanceSignatureHelp
if *buildTags != "" {
cfg.BuildTags = strings.Split(*buildTags, " ")
}
if err := run(cfg); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run(cfg langserver.Config) error {
if *printVersion {
fmt.Println(version)
return nil
}
var logW io.Writer
if *logfile == "" {
logW = os.Stderr
} else {
f, err := os.Create(*logfile)
if err != nil {
return err
}
defer f.Close()
logW = io.MultiWriter(os.Stderr, f)
}
log.SetOutput(logW)
var connOpt []jsonrpc2.ConnOpt
if *trace {
connOpt = append(connOpt, jsonrpc2.LogMessages(log.New(logW, "", 0)))
}
newHandler := func() jsonrpc2.Handler {
return langserver.NewHandler(cfg)
}
switch *mode {
case "tcp":
lis, err := net.Listen("tcp", *addr)
if err != nil {
return err
}
defer lis.Close()
log.Println("langserver-go: listening on", *addr)
for {
conn, err := lis.Accept()
if err != nil {
return err
}
jsonrpc2.NewConn(context.Background(), jsonrpc2.NewBufferedStream(conn, jsonrpc2.VSCodeObjectCodec{}), newHandler(), connOpt...)
}
case "stdio":
log.Println("langserver-go: reading on stdin, writing on stdout")
<-jsonrpc2.NewConn(context.Background(), jsonrpc2.NewBufferedStream(stdrwc{}, jsonrpc2.VSCodeObjectCodec{}), newHandler(), connOpt...).DisconnectNotify()
log.Println("connection closed")
return nil
default:
return fmt.Errorf("invalid mode %q", *mode)
}
}
type stdrwc struct{}
func (stdrwc) Read(p []byte) (int, error) {
return os.Stdin.Read(p)
}
func (stdrwc) Write(p []byte) (int, error) {
return os.Stdout.Write(p)
}
func (stdrwc) Close() error {
if err := os.Stdin.Close(); err != nil {
return err
}
return os.Stdout.Close()
}
// freeOSMemory should be called in a goroutine, it invokes
// runtime/debug.FreeOSMemory() more aggressively than the runtime default of
// 5 minutes after GC.
//
// There is a long-standing known issue with Go in which memory is not returned
// to the OS aggressively enough[1], which coincidently harms our application
// quite a lot because we perform so many short-burst heap allocations during
// the type-checking phase.
//
// This function should only be invoked in editor mode, not in sourcegraph.com
// mode, because users running the language server as part of their editor
// generally expect much lower memory usage. In contrast, on sourcegraph.com we
// can give our servers plenty of RAM and allow Go to consume as much as it
// wants. Go does reuse the memory not free'd to the OS, and as such enabling
// this does _technically_ make our application perform less optimally -- but
// in practice this has no observable effect in editor mode.
//
// The end effect of performing this is that repeating "hover over code" -> "make an edit"
// 10 times inside a large package like github.com/docker/docker/cmd/dockerd:
//
//
// | Real Before | Real After | Real Change | Go Before | Go After | Go Change |
// |-------------|------------|-------------|-----------|----------|-----------|
// | 7.61GB | 4.12GB | -45.86% | 3.92GB | 3.33GB | -15.05% |
//
// Where `Real` means real memory reported by OS X Activity Monitor, and `Go`
// means memory reported by Go as being in use.
//
// TL;DR: 46% less memory consumption for users running with the vscode-go extension.
//
// [1] https://github.com/golang/go/issues/14735#issuecomment-194470114
func freeOSMemory() {
for {
time.Sleep(time.Duration(*freeosmemory) * time.Second)
debug.FreeOSMemory()
}
}