summaryrefslogtreecommitdiff
path: root/server/src/service.lua
blob: 6c7b83d7aa408a2348d2c232abb5d4002e5547b5 (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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
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 core       = require 'core'
local lang       = require 'language'
local updateTimer = require 'timer'

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, debug.traceback, 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 ok, r = pcall(table.dump, params)
            local dump = ok and r or 'Cyclic table'
            log.debug(('Task [%s] failed, params: %s'):format(
                name, dump
            ))
            log.debug(res)
            return nil, {
                code = ErrorCodes.InternalError,
                message = r .. '\n' .. res,
            }
        end
    end
    if optional then
        return nil
    else
        return nil, {
            code = ErrorCodes.MethodNotFound,
            message = 'MethodNotFound',
        }
    end
end

function mt:responseProto(id, response, err)
    local container = table.container()
    if err then
        container.error = err
    else
        container.result = response
    end
    rpc:response(id, container)
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
    if type(response) == 'function' then
        return function (final)
            self:responseProto(id, final)
        end
    else
        self:responseProto(id, response, err)
    end
end

function mt:clearDiagnostics(uri)
    rpc:notify('textDocument/publishDiagnostics', {
        uri = uri,
        diagnostics = {},
    })
    log.debug('清除诊断:', uri)
end

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

function mt:needCompile(uri, compiled)
    if self._needCompile[uri] then
        return
    end
    if not compiled then
        compiled = {}
    end
    if compiled[uri] then
        return
    end
    self._needCompile[uri] = compiled
    table.insert(self._needCompile, 1, uri)
end

function mt:isWaitingCompile()
    if self._needCompile[1] then
        return true
    else
        return false
    end
end

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

function mt:open(uri, version, text)
    self:saveText(uri, version, text)
    local obj = self._file[uri]
    if obj then
        obj._openByClient = true
    end
end

function mt:close(uri)
    local obj = self._file[uri]
    if obj then
        obj._openByClient = false
    end
end

function mt:isOpen(uri)
    local obj = self._file[uri]
    if obj and obj._openByClient then
        return true
    else
        return false
    end
end

function mt:readText(uri, path, buf)
    local obj = self._file[uri]
    if obj then
        return
    end
    local text = buf or io.load(path)
    if not text then
        log.debug('无法找到文件:', path)
        return
    end
    self._file[uri] = {
        version = -1,
        text = text,
        uri = uri,
    }
    self:needCompile(uri)
end

function mt:removeText(uri)
    self._file[uri] = nil
    -- 删除文件后,清除该文件的诊断
    self:clearDiagnostics(uri)
    -- 清除全局变量
    self._global:clearGlobal(uri)
end

function mt:reCompile()
    local compiled = {}
    local n = 0
    for uri in pairs(self._file) do
        self:needCompile(uri, compiled)
        n = n + 1
    end
    log.debug('reCompile:', n)

    if self._needShowComplete then
        self._needShowComplete = nil
        rpc:notify('window/showMessage', {
            type = 3,
            message = lang.script.MWS_COMPLETE,
        })
    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, obj.text
end

function mt:_markCompiled(uri)
    local compiled = self._needCompile[uri]
    if compiled then
        compiled[uri] = true
        self._needCompile[uri] = nil
    end
    for i, u in ipairs(self._needCompile) do
        if u == uri then
            table.remove(self._needCompile, i)
            break
        end
    end
    return compiled
end

function mt:compileAst(obj)
    local ast, err = parser:ast(obj.text)
    obj.astErr = err
    if not ast then
        if type(err) == 'string' then
            local message = lang.script('PARSER_CRASH', err)
            log.debug(message)
            rpc:notify('window/showMessage', {
                type = 3,
                message = lang.script('PARSER_CRASH', err:match 'grammar%.lua%:%d+%:(.+)'),
            })
        end
    end
    return ast
end

function mt:_clearChainNode(obj, uri)
    if obj.parent then
        for pUri in pairs(obj.parent) do
            local parent = self._file[pUri]
            if parent and parent.child then
                parent.child[uri] = nil
            end
        end
    end
end

function mt:_compileChain(obj, compiled)
    if not obj.child then
        return
    end
    if not compiled then
        compiled = {}
    end
    local list = {}
    for child in pairs(obj.child) do
        list[#list+1] = child
    end
    table.sort(list)
    for _, child in ipairs(list) do
        self:needCompile(child, compiled)
    end
end

function mt:_compileGlobal(obj, compiled)
    local needReCompile = self._global:compileVM(obj.uri, obj.vm)
    for _, uri in ipairs(needReCompile) do
        self:needCompile(uri, compiled)
    end
end

function mt:getGlobal(key)
    local tp = type(key)
    if tp == 'string' or tp == 'number' or tp == 'boolean' then
        return self._global:getGlobal(key)
    else
        return nil
    end
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

    local clock = os.clock()
    local ast = self:compileAst(obj)
    obj.astCost = os.clock() - clock
    self:_clearChainNode(obj, uri)
    self._global:clearGlobal(uri)

    local clock = os.clock()
    obj.vm = core.vm(ast, self, uri)
    obj.vmCost = os.clock() - clock

    local clock = os.clock()
    obj.lines = parser:lines(obj.text, 'utf8')
    obj.lineCost = os.clock() - clock

    local compiled = self:_markCompiled(uri)
    self._needDiagnostics[uri] = true

    if not obj.vm then
        return obj
    end

    self:_compileChain(obj, compiled)
    self:_compileGlobal(obj, compiled)

    return obj
end

function mt:doDiagnostics(uri)
    if not self._needDiagnostics[uri] then
        return
    end
    self._needDiagnostics[uri] = nil
    local name = 'textDocument/publishDiagnostics'
    local vm, lines = self:getVM(uri)
    if not vm then
        self:clearDiagnostics(uri)
        return
    end
    local data = {
        uri   = uri,
        vm    = vm,
        lines = lines,
    }
    local res  = self:_callMethod(name, data)
    if res then
        rpc:notify(name, {
            uri = uri,
            diagnostics = res,
        })
    else
        self:clearDiagnostics(uri)
    end
end

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

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

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

function mt:compileChain(child, parent)
    local parentObj = self._file[parent]
    local childObj = self._file[child]

    if not parentObj or not childObj then
        return
    end
    if parentObj == childObj then
        return
    end

    if not parentObj.child then
        parentObj.child = {}
    end
    parentObj.child[child] = true

    if not childObj.parent then
        childObj.parent = {}
    end
    childObj.parent[parent] = true
end

function mt:checkWorkSpaceComplete()
    if self._hasCheckedWorkSpaceComplete then
        return
    end
    self._hasCheckedWorkSpaceComplete = true
    if self.workspace:isComplete() then
        return
    end
    self._needShowComplete = true
    rpc:notify('window/showMessage', {
        type = 3,
        message = lang.script.MWS_NOT_COMPLETE,
    })
end

function mt:_createCompileTask()
    if not self:isWaitingCompile() and not next(self._needDiagnostics) then
        return
    end
    self._compileTask = coroutine.create(function ()
        local uri = self._needCompile[1]
        if uri then
            self:compileVM(uri)
        end
        local uri = next(self._needDiagnostics)
        if uri then
            self:doDiagnostics(uri)
        end
    end)
end

function mt:_doCompileTask()
    if not self._compileTask then
        self:_createCompileTask()
    end
    if not self._compileTask then
        return
    end
    while true do
        local suc, res = coroutine.resume(self._compileTask)
        if not suc then
            break
        end
        if coroutine.status(self._compileTask) == 'suspended' then
            self:_loadProto()
        else
            self._compileTask = nil
            return
        end
    end
end

function mt:_loadProto()
    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
end

function mt:onTick()
    self:_loadProto()
    self:_doCompileTask()

    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'

    local _, out = async.run 'proto'
    self._proto = out

    local clock = os.clock()
    while true do
        async.onTick()
        self:onTick()

        local delta = os.clock() - clock
        clock = os.clock()
        updateTimer(delta)
        thread.sleep(0.001)
    end
end

return function ()
    local session = setmetatable({
        _file = {},
        _needCompile = {},
        _needDiagnostics = {},
        _clock = -100,
        _version = 0,
        _global = core.global(),
    }, mt)
    return session
end