summaryrefslogtreecommitdiff
path: root/script/plugins/ffi/init.lua
blob: 57a64958a7f5451c7b5511a42b4e51c8ffa87b57 (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
local searchCode        = require 'plugins.ffi.searchCode'
local cdefRerence       = require 'plugins.ffi.cdefRerence'
local cdriver           = require 'plugins.ffi.c-parser.cdriver'
local util              = require 'utility'
local SDBMHash          = require 'SDBMHash'
local ws                = require 'workspace'
local files             = require 'files'
local await             = require 'await'
local config            = require 'config'
local fs                = require 'bee.filesystem'
local scope             = require 'workspace.scope'

local namespace <const> = 'ffi.namespace*.'

local function nkeys(t)
    local n = 0
    for key, value in pairs(t) do
        n = n + 1
    end
    return n
end

local function isSingleNode(ast)
    if type(ast) ~= 'table' then
        return false
    end
    local len = #ast
    return len == 1 and len == nkeys(ast)
end

--TODO:supprot 32bit ffi, need config
local knownTypes        = {
    ["bool"] = 'boolean',
    ["char"] = 'integer',
    ["short"] = 'integer',
    ["int"] = 'integer',
    ["long"] = 'integer',
    ["float"] = 'number',
    ["double"] = 'number',
    ["signed"] = 'integer',
    ["__signed"] = 'integer',
    ["__signed__"] = 'integer',
    ["unsigned"] = 'integer',
    ["ptrdiff_t"] = 'integer',
    ["size_t"] = 'integer',
    ["ssize_t"] = 'integer',
    ["wchar_t"] = 'integer',
    ["int8_t"] = 'integer',
    ["int16_t"] = 'integer',
    ["int32_t"] = 'integer',
    ["int64_t"] = 'integer',
    ["uint8_t"] = 'integer',
    ["uint16_t"] = 'integer',
    ["uint32_t"] = 'integer',
    ["uint64_t"] = 'integer',
    ["intptr_t"] = 'integer',
    ["uintptr_t"] = 'integer',
    ["__int8"] = 'integer',
    ["__int16"] = 'integer',
    ["__int32"] = 'integer',
    ["__int64"] = 'integer',
    ["_Bool"] = 'boolean',
    ["__ptr32"] = 'integer',
    ["__ptr64"] = 'integer',
    --[[
    ["_Complex"] = 1,
    ["complex"] = 1,
    ["__complex"] = 1,
    ["__complex__"] = 1,
]]
    ["unsignedchar"] = 'integer',
    ["unsignedshort"] = 'integer',
    ["unsignedint"] = 'integer',
    ["unsignedlong"] = 'integer',
    ["signedchar"] = 'integer',
    ["signedshort"] = 'integer',
    ["signedint"] = 'integer',
    ["signedlong"] = 'integer',
}

local constName <const> = 'm'

---@class ffi.builder
local builder           = { switch_ast = util.switch() }

function builder:getTypeAst(name)
    for i, asts in ipairs(self.globalAsts) do
        if asts[name] then
            return asts[name]
        end
    end
end

function builder:needDeref(ast)
    if not ast then
        return false
    end
    if ast.type == 'typedef' then
        -- maybe no name
        ast = ast.def[1]
        if type(ast) ~= 'table' then
            return self:needDeref(self:getTypeAst(ast))
        end
    end
    if ast.type == 'struct' or ast.type == 'union' then
        return true
    else
        return false
    end
end

function builder:getType(name)
    if type(name) == 'table' then
        local t = ""
        local isStruct
        for _, n in ipairs(name) do
            if type(n) == 'table' then
                n = n.full_name
            end
            if not isStruct then
                isStruct = self:needDeref(self:getTypeAst(n))
            end
            t = t .. n
        end
        -- deref 一级指针
        if isStruct and t:sub(#t) == '*' then
            t = t:sub(1, #t - 1)
        end
        name = t
    end
    if knownTypes[name] then
        return knownTypes[name]
    end
    return namespace .. name
end

function builder:isVoid(ast)
    if not ast then
        return false
    end
    if ast.type == 'typedef' then
        return self:isVoid(self:getTypeAst(ast.def[1]) or ast.def[1])
    end

    local typename = type(ast.type) == 'table' and ast.type[1] or ast
    if typename == 'void' then
        return true
    end
    return self:isVoid(self:getTypeAst(typename))
end

function builder:buildStructOrUnion(lines, tt, name)
    lines[#lines+1] = '---@class ' .. self:getType(name)
    for _, field in ipairs(tt.fields or {}) do
        if field.name and field.type then
            lines[#lines+1] = ('---@field %s %s'):format(field.name, self:getType(field.type))
        end
    end
end

function builder:buildFunction(lines, tt, name)
    local param_names = {}
    for i, param in ipairs(tt.params or {}) do
        lines[#lines+1] = ('---@param %s %s'):format(param.name, self:getType(param.type))
        param_names[#param_names+1] = param.name
    end
    if tt.vararg then
        param_names[#param_names+1] = '...'
    end
    if tt.ret then
        if not self:isVoid(tt.ret) then
            lines[#lines+1] = ('---@return %s'):format(self:getType(tt.ret.type))
        end
    end
    lines[#lines+1] = ('function m.%s(%s) end'):format(name, table.concat(param_names, ', '))
end

function builder:buildTypedef(lines, tt, name)
    local def = tt.def[1]
    if type(def) == 'table' and not def.name then
        -- 这个时候没有主类型,只有一个别名,直接创建一个别名结构体
        self.switch_ast(def.type, self, lines, def, name)
    else
        lines[#lines+1] = ('---@alias %s %s'):format(name, self:getType(def))
    end
end

local calculate

local function binop(enumer, val, fn)
    local e1, e2 = calculate(enumer, val[1]), calculate(enumer, val[2])
    if type(e1) == "number" and type(e2) == "number" then
        return fn(e1, e2)
    else
        return { e1, e2, op = val.op }
    end
end
do
    local ops = {
        ['+'] = function (a, b) return a + b end,
        ['-'] = function (a, b) return a - b end,
        ['*'] = function (a, b) return a * b end,
        ['/'] = function (a, b) return a / b end,
        ['&'] = function (a, b) return a & b end,
        ['|'] = function (a, b) return a | b end,
        ['~'] = function (a, b)
            if not b then
                return ~a
            end
            return a ~ b
        end,
        ['<<'] = function (a, b) return a << b end,
        ['>>'] = function (a, b) return a >> b end,
    }
    calculate = function (enumer, val)
        if ops[val.op] then
            return binop(enumer, val, ops[val.op])
        end
        if isSingleNode(val) then
            val = val[1]
        end
        if type(val) == "string" then
            if enumer[val] then
                return enumer[val]
            end
            return tonumber(val)
        end
        return val
    end
end

local function pushEnumValue(enumer, name, v)
    if isSingleNode(v) then
        v = tonumber(v[1])
    end
    enumer[name] = v
    enumer[#enumer+1] = v
    return v
end

function builder:buildEnum(lines, tt, name)
    local enumer = {}
    for i, val in ipairs(tt.values) do
        local name = val.name
        local v = val.value
        if not v then
            if i == 1 then
                v = 0
            else
                v = tt.values[i - 1].realValue + 1
            end
        end
        if type(v) == 'table' and v.op then
            v = calculate(enumer, v)
        end
        if v then
            val.realValue = pushEnumValue(enumer, name, v)
        end
    end
    local alias = {}
    for k, v in pairs(enumer) do
        alias[#alias+1] = type(k) == 'number' and v or ([['%s']]):format(k)
        if type(k) ~= 'number' then
            lines[#lines+1] = ('m.%s = %s'):format(k, v)
        end
    end
    if name then
        lines[#lines+1] = ('---@alias %s %s'):format(self:getType(name), table.concat(alias, ' | '))
    end
end

builder.switch_ast
    :case 'struct'
    :case 'union'
    :call(builder.buildStructOrUnion)
    :case 'enum'
    :call(builder.buildEnum)
    : case 'function'
    :call(builder.buildFunction)
    :case 'typedef'
    :call(builder.buildTypedef)

local function stringStartsWith(self, searchString, position)
    if position == nil or position < 0 then
        position = 0
    end
    return string.sub(self, position + 1, #searchString + position) == searchString
end
local firstline = ('---@meta \n ---@class %s \n local %s = {}'):format(namespace, constName)
local m = {}
local function compileCode(lines, asts, b)
    for _, ast in ipairs(asts) do
        local tt = ast.type

        if tt.type == 'enum' and not stringStartsWith(ast.name, 'enum@') then
            goto continue
        end
        if not tt.name then
            if tt.type ~= 'enum' then
                goto continue
            end
            --匿名枚举也要创建具体的值
            lines = lines or { firstline }
            builder.switch_ast(tt.type, b, lines, tt)
        else
            tt.full_name = ast.name
            lines = lines or { firstline }
            builder.switch_ast(tt.type, b, lines, tt, tt.full_name)
            lines[#lines+1] = '\n'
        end
        ::continue::
    end
    return lines
end
function m.compileCodes(codes)
    ---@class ffi.builder
    local b = setmetatable({ globalAsts = {}, cacheEnums = {} }, { __index = builder })

    local lines
    for _, code in ipairs(codes) do
        local asts = cdriver.process_context(code)
        if not asts then
            goto continue
        end
        table.insert(b.globalAsts, asts)
        lines = compileCode(lines, asts, b)
        ::continue::
    end
    return lines
end

local function createDir(uri)
    local dir     = scope.getScope(uri).uri or 'default'
    local fileDir = fs.path(METAPATH) / ('%08x'):format(SDBMHash():hash(dir))
    fs.create_directories(fileDir)
    return fileDir
end

local builder
function m.initBuilder(fileDir)
    fileDir = fileDir or createDir()
    ---@async
    return function (uri)
        local refs = cdefRerence()
        if not refs or #refs == 0 then
            return
        end

        local codes = searchCode(refs, uri)
        if not codes then
            return
        end

        local texts = m.compileCodes(codes)
        if not texts then
            return
        end
        local hash = ('%08x'):format(SDBMHash():hash(uri))
        local encoding = config.get(nil, 'Lua.runtime.fileEncoding')
        local filePath = fileDir / table.concat({ hash, encoding }, '_')

        util.saveFile(tostring(filePath) .. '.d.lua', table.concat(texts, '\n'))
    end
end

files.watch(function (ev, uri)
    if ev == 'compiler' or ev == 'update' then
        if builder then
            await.call(function () ---@async
                builder(uri)
            end)
        end
    end
end)

ws.watch(function (ev, uri)
    if ev == 'startReload' then
        if config.get(uri, 'Lua.runtime.version') ~= 'LuaJIT' then
            return
        end
        await.call(function () ---@async
            ws.awaitReady(uri)
            local fileDir = createDir(uri)
            builder = m.initBuilder(fileDir)
            local client = require 'client'
            client.setConfig {
                {
                    key    = 'Lua.workspace.library',
                    action = 'add',
                    value  = tostring(fileDir),
                    uri    = uri,
                }
            }
        end)
    end
end)

return m