summaryrefslogtreecommitdiff
path: root/server/src/service.lua
blob: 43b59d528bd2d5cc9fd7c1e9b8e6d5cc83916988 (plain)
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
local subprocess = require 'bee.subprocess'
local method     = require 'method'
local thread     = require 'bee.thread'
local async      = require 'async'
local rpc        = require 'rpc'
local parser     = require 'parser'
local matcher    = require 'matcher'

thread.newchannel 'proto'

local ErrorCodes = {
    -- Defined by JSON RPC
    ParseError           = -32700,
    InvalidRequest       = -32600,
    MethodNotFound       = -32601,
    InvalidParams        = -32602,
    InternalError        = -32603,
    serverErrorStart     = -32099,
    serverErrorEnd       = -32000,
    ServerNotInitialized = -32002,
    UnknownErrorCode     = -32001,

    -- Defined by the protocol.
    RequestCancelled     = -32800,
}

local mt = {}
mt.__index = mt

function mt:_callMethod(name, params)
    local optional
    if name:sub(1, 2) == '$/' then
        name = name:sub(3)
        optional = true
    end
    local f = method[name]
    if f then
        local clock = os.clock()
        local suc, res = xpcall(f, log.error, self, params)
        local passed = os.clock() - clock
        if passed > 0.1 then
            log.debug(('Task [%s] takes [%.3f]sec.'):format(name, passed))
        end
        if suc then
            return res
        else
            local suc, res = pcall(table.dump, params)
            local dump = suc and res or 'Cyclic table'
            log.debug(('Task [%s] failed, params: %s'):format(
                name, dump
            ))
            return nil, {
                code = ErrorCodes.InternalError,
                message = res,
            }
        end
    end
    if optional then
        return nil
    else
        return nil, {
            code = ErrorCodes.MethodNotFound,
            message = 'MethodNotFound',
        }
    end
end

function mt:_doProto(proto)
    local id     = proto.id
    local name   = proto.method
    local params = proto.params
    local response, err = self:_callMethod(name, params)
    if not id then
        return
    end
    local container = table.container()
    if err then
        container.error = err
    else
        container.result = response
    end
    rpc:response(id, container)
end

function mt:_doDiagnostic()
    if not next(self._needDiagnostics) then
        return
    end
    local clock = os.clock()
    local count = 0
    local copy = {}
    for uri in pairs(self._needDiagnostics) do
        self._needDiagnostics[uri] = nil
        count = count + 1
        copy[uri] = true
    end
    for uri in pairs(copy) do
        local obj = self._file[uri]
        if obj then
            local data = {
                uri   = uri,
                vm    = obj.vm,
                lines = obj.lines,
            }
            local name = 'textDocument/publishDiagnostics'
            local res  = self:_callMethod(name, data)
            if res then
                rpc:notify(name, {
                    uri = uri,
                    diagnostics = res,
                })
            end
        end
    end
    local passed = os.clock() - clock
    if passed > 0.1 then
        log.debug(('\n\z
        Diagnostics completion\n\z
        Cost:  [%.3f]sec\n\z
        Num:   [%d]'):format(
            passed,
            count
        ))
    end
end

function mt:clearDiagnostics(uri)
    rpc:notify('textDocument/publishDiagnostics', {
        uri = uri,
        diagnostics = {},
    })
end

function mt:_buildTextCache()
    if not next(self._needCompile) then
        return
    end
    local list = {}
    for uri in pairs(self._needCompile) do
        list[#list+1] = uri
    end

    local size = 0
    local clock = os.clock()
    for _, uri in ipairs(list) do
        local obj = self:compileVM(uri)
        size = size + #obj.text
    end
    local passed = os.clock() - clock
    if passed > 0.1 then
        log.debug(('\n\z
        Cache completion\n\z
        Cost:  [%.3f]sec\n\z
        Num:   [%d]\n\z
        Size:  [%.3f]kb'):format(
            passed,
            #list,
            size / 1000
        ))
    end
end

function mt:read(mode)
    if not self._input then
        return nil
    end
    return self._input(mode)
end

function mt:saveText(uri, version, text)
    local obj = self._file[uri]
    if obj then
        if obj.version >= version then
            return
        end
        obj.version = version
        obj.text = text
        self._needCompile[uri] = true
    else
        self._file[uri] = {
            version = version,
            text = text,
        }
        self._needCompile[uri] = true
    end
end

function mt:readText(uri, path)
    local obj = self._file[uri]
    if obj then
        return
    end
    local text = io.load(path)
    if not text then
        return
    end
    self._file[uri] = {
        version = -1,
        text = text,
    }
    self._needCompile[uri] = true
end

function mt:open(uri)
    self._opening[uri] = true
end

function mt:close(uri)
    self._opening[uri] = nil
end

function mt:isOpen(uri)
    return self._opening[uri] == true
end

function mt:reCompile()
    for uri in pairs(self._opening) do
        self._needCompile[uri] = true
    end
end

function mt:loadVM(uri)
    local obj = self._file[uri]
    if not obj then
        return nil
    end
    self:compileVM(uri)
    return obj.vm, obj.lines
end

function mt:compileVM(uri)
    local obj = self._file[uri]
    if not obj then
        return nil
    end
    if not self._needCompile[uri] then
        return nil
    end
    self._needCompile[uri] = nil
    local ast = parser:ast(obj.text)

    obj.vm = matcher.vm(ast, self, uri)
    obj.lines = parser:lines(obj.text, 'utf8')
    if not obj.vm then
        return obj
    end

    self._needDiagnostics[uri] = true

    return obj
end

function mt:getVM(uri)
    local obj = self._file[uri]
    if not obj then
        return nil
    end
    if self._needCompile[uri] then
        return nil
    end
    return obj.vm
end

function mt:needRequires(uri)
    self._needRequire[uri] = true
end

function mt:_loadRequires()
    if not self.workspace then
        return
    end
    if not next(self._needRequire) then
        return
    end
    local copy = {}
    for uri in pairs(self._needRequire) do
        self._needRequire[uri] = nil
        copy[uri] = true
    end
    for uri in pairs(copy) do
        local obj = self._file[uri]
        if obj then
            obj.vm:loadRequires(self)
            self._needDiagnostics[uri] = true
        end
    end
end

function mt:removeText(uri)
    self._file[uri] = nil
end

function mt:onTick()
    while true do
        local ok, proto = self._proto:pop()
        if not ok then
            break
        end
        if proto.method then
            self:_doProto(proto)
        else
            rpc:recieve(proto)
        end
    end
    self:_buildTextCache()
    self:_doDiagnostic()
    self:_loadRequires()

    if os.clock() - self._clock >= 600 then
        self._clock = os.clock()
        local count = 0
        for _ in pairs(self._file) do
            count = count + 1
        end
        local mem = collectgarbage 'count'
        log.debug(('\n\z
        State\n\z
        Mem:   [%.3f]kb\n\z
        Cache: [%d]'):format(
            mem,
            count
        ))
    end
end

function mt:listen()
    subprocess.filemode(io.stdin, 'b')
    subprocess.filemode(io.stdout, 'b')
    io.stdin:setvbuf 'no'
    io.stdout:setvbuf 'no'

    self._proto = thread.channel 'proto'

    async.call([[require 'proto']])

    while true do
        async.onTick()
        self:onTick()
        thread.sleep(0.001)
    end
end

return function ()
    local session = setmetatable({
        _file = {},
        _needCompile = {},
        _needRequire = {},
        _needDiagnostics = {},
        _opening = {},
        _clock = -100,
    }, mt)
    return session
end