aboutsummaryrefslogtreecommitdiff
path: root/convert/spec.lua
blob: d7ba4325bc7ac37627e5164d88eb88207efc45a5 (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
local function snext(t, state)
	local key

	if state == nil then
		t.__sorted = {}
		for k in pairs(t) do
			if k ~= "__sorted" then
				table.insert(t.__sorted, k)
			end
		end
		table.sort(t.__sorted)

		key = t.__sorted[1]
	else
		for i, v in ipairs(t.__sorted) do
			if v == state then
				key = t.__sorted[i + 1]
				break
			end
		end
	end

	if key then
		return key, t[key]
	end

	t.__sorted = nil
end

function spairs(t)
	return snext, t, nil
end

local function parse_pair(pair, value_first)
	if pair:sub(1, 1) == "#" then
		return
	end

	local idx = pair:find(" ")

	if idx then
		local first, second = pair:sub(1, idx - 1), pair:sub(idx + 1)
		local c = first:sub(1, 1)

		if value_first and c ~= "{" and c ~= "%" then
			return second, first
		else
			return first, second
		end
	else
		return pair
	end
end

function parse_spec(name, value_first)
	local f = io.open("spec/" .. name, "r")
	local spec = {}
	local top

	for l in f:lines() do
		if l:sub(1, 1) == "\t" then
			local key, val = parse_pair(l:sub(2), value_first)

			if val then
				top[key] = val
			elseif key then
				table.insert(top, key)
			end
		else
			local key, val = parse_pair(l, value_first)

			if val then
				spec[key] = val
			elseif key then
				top = {}
				spec[key] = top
			end
		end
	end

	f:close()
	return spec
end

local casemap = parse_spec("casemap")

function camel_case(snake)
	if casemap[snake] then
		return casemap[snake]
	end

	local camel = ""

	while #snake > 0 do
		local idx = snake:find("_") or #snake + 1

		camel = camel
			.. snake:sub(1, 1):upper()
			.. snake:sub(2, idx - 1)

		snake = snake:sub(idx + 1)
	end

	return camel
end

function apply_prefix(fields, str)
	return (fields.prefix or "") .. camel_case(str) .. (fields.postfix or "")
end