-
Notifications
You must be signed in to change notification settings - Fork 49
/
lautoc.lua
105 lines (74 loc) · 2.41 KB
/
lautoc.lua
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
#!/usr/bin/env lua
-- LuaAutoC - Automagically use C Functions and Structs with the Lua API
-- https://github.com/orangeduck/LuaAutoC
-- Daniel Holden - [email protected]
-- Licensed under BSD
-- Findall Function
function findall(text, pattern)
local matches = {}
for word in string.gmatch(text, pattern) do
table.insert(matches, word)
end
return matches
end
-- String Split Function
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- Check Arguments
if #arg ~= 1 then
print('Usage: lua lautoc.lua <header.h>')
return
end
-- Open Header
local file = io.open(arg[1], 'r')
if file == nil then
print(string.format('Error: Cannot load file "%s"', arg[1]))
return
end
local text = file:read('*all')
io.close(file)
-- Remove all newlines
local text = string.gsub(text, "\r", "")
local text = string.gsub(text, "\n", "")
-- Find all typedefs, structs, and functions
typestrts = findall(text, "typedef struct {.-} %w-;")
typeenums = findall(text, "typedef enum {.-} %w-;")
funcs = findall(text, "[%w%*]- [%w_]-%(.-%);")
-- Output Typedef Enum Code
for k,v in pairs(typeenums) do
local _, _, members, typename = string.find(v, "typedef enum {(.-)} (%w-);")
print(string.format("luaA_enum(%s);", typename))
for _, mem in pairs(members:split(",")) do
local _, _, name = string.find(mem, "(%w+)")
print(string.format("luaA_enum_value(%s, %s);", typename, name))
end
print("")
end
-- Output Typedef Struct Code
for k,v in pairs(typestrts) do
local _, _, members, typename = string.find(v, "typedef struct {(.-)} (%w-);")
print(string.format("luaA_struct(%s);", typename))
for _, mem in pairs(members:split(";")) do
local meminfo = mem:split(" ")
print(string.format("luaA_struct_member(%s, %s, %s);", typename, meminfo[2], meminfo[1]))
end
print("")
end
-- Output Function Code
for k,v in pairs(funcs) do
local _, _, typename, name, args = string.find(v, "([%w%*]-) ([%w_]-)%((.-)%);")
local argtypes = {}
for _, arg in pairs(args:split(",")) do
table.insert(argtypes, arg:split(" ")[1])
end
local fstring = string.format("luaA_function(%s, %s", name, typename)
for _, v in pairs(argtypes) do
fstring = fstring .. string.format(", %s", v)
end
local fstring = fstring .. ");"
print(fstring)
end