-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenrule.lua
124 lines (106 loc) · 2.29 KB
/
genrule.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
--[[
DSL for creating make rules
```
r = Rule {
"@touch $$@"
}
```
will create a (uniquely named) rule. `tostring(r)` will yield
an `$(eval)`uatable make expression that defines the rule
```
_anon_lua_rule_1:
@touch $@
```
key-value pairs are turned into target-specific variables:
```
r = Rule {
FOO="bar",
{
"@echo hello from $$@'s rule",
"@echo the value of FOO is $$(FOO)",
"@touch $$@",
}
}
```
tostring(r):
```
_anon_lua_rule_1:FOO=bar
_anon_lua_rule_1:
@echo hello from $@'s rule
@echo the value of FOO is $(FOO)
@touch $@
```
]]
local M = {}
local i = 1
function M.beep()
print(string.format("beep %d", i))
i = i + 1
end
local MTi_rule = {}
local MT_rule = {__index = MTi_rule}
function MT_rule:__tostring()
return table.concat({
self:head(),
self:recipe(),
}, "\n")
end
-- the "head" is a bunch of rule:VAR=value lines
function MTi_rule:head()
local head = {}
for k,v in pairs(self.locals) do
table.insert(head, string.format("%s:%s=%s", self.name, k, tostring(v)))
end
return table.concat(head, "\n")
end
-- generates the actual recipe
function MTi_rule:recipe()
local ret = {
self.name..":"
}
for _, cmd in ipairs(self.commands) do
table.insert(ret, cmd)
end
return table.concat(ret, "\n\t")
end
local anonRuleCount = 0
local function mkname()
anonRuleCount = anonRuleCount + 1
return "_anon_lua_rule_" .. tostring(anonRuleCount)
end
local function mkrule(name, cfg)
local locals = {}
for k,v in pairs(cfg) do
if type(k) == "string" then
locals[k] = v
end
end
local commands = type(cfg[1]) == "table" and cfg[1] or {cfg[1]}
local ret = {
name = name,
locals = locals,
commands = commands,
}
return setmetatable(ret, MT_rule)
end
function M.rule(name)
if type(name) == "table" then
return mkrule(mkname(), name)
end
return function(cfg)
return mkrule(name, cfg)
end
end
local function iter(name)
local ex = expand(string.format("$(patsubst %%,{%%},$(%s))", name))
return ex:gmatch "{([^}]*)}"
end
function M.list(name)
local ret = {}
for el in iter(name) do
table.insert(ret, el)
end
return ret
end
M.iter = iter
return M