summaryrefslogtreecommitdiff
path: root/cook.py
blob: 9a0d66d3dacd451c38552c0ede3d918824bf30d7 (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
#!/usr/bin/python

import os
from pathlib import Path
from threading import local
import shutil
import argparse

def find_program(prog, required=True):
    path = shutil.which(prog)
    if path == None and required:
        raise Exception("Required program '%s' not found on the system" % (prog))
    return File(path)

def flatten(el):
    if type(el) == list or type(el) == tuple:
        return [a for b in el for a in flatten(b)]
    else:
        return [el]

ROOT = Path.cwd()
BUILD = Path("bld").resolve().relative_to(ROOT)
DEFDESC = lambda o, i, cmd: "%s" % (cmd)

#self, name, exe, mkargs, mkout, mkinc, desc=DEFDESC

C_COMPILERS = {
    'gcc': lambda: CC(
        "gcc",
        exe=find_program("gcc"),
        mkargs=lambda o, i, ea: "-MD -MF %s.d -o %s -c %s %s" % (o, o, i, ea),
        mkout=lambda i: i.name + ".o",
        mkinc=lambda i: "-I" + i,
        mkdep=lambda o: "%s.d" % (o),
        depstyle="gcc",
        desc=lambda o, i, cmd: "CC %s" % (o),
    ),
    'clang': lambda: CC(
        "clang",
        find_program("clang"),
        lambda o, i, ea: "-MD -MF %s.d -o %s -c %s %s" % (o, i, ea),
        mkargs=lambda o, i, ea: "-MD -MF %s.d -o %s -c %s %s" % (o, o, i, ea),
        mkout=lambda i: i.name + ".o",
        mkinc=lambda i: "-I" + i,
        mkdep=lambda o: "%s.d" % (o),
        depstyle="gcc",
        desc=lambda o, i, cmd: "CC %s" % (o),
    )
}

C_LINKERS = {
    'gcc': lambda: Machine(
        "ld-gcc",
        find_program("gcc"),
        lambda o, i, ea: "-o %s %s %s" % (o, i, ea),
        lambda o, i, cmd: "LD %s" % (o)
    ),
    'clang': lambda: Machine(
        "ld-clang",
        find_program("clang"),
        lambda o, i, ea: "-o %s %s %s" % (o, i, ea),
        lambda o, i, cmd: "LD %s" % (o)
    )
}

def wrap_lambda(s):
    if callable(s):
        return s
    else:
        return lambda *args: s


class FileMeta(type):
    def __call__(cls, path, *rest, **krest):
        # If none, return none
        if path == None:
            return None
    
        # If already a file, return it
        if issubclass(type(path), File):
            return path
    
        # Adjust name to be a path
        if type(path) == str:
            p = Path(path).resolve()
            if p.is_relative_to(ROOT):
                path = p.relative_to(ROOT)
            else:
                path = p
    
        idx = str(path) + cls.__name__
    
        if idx in cls.fdb:
            return cls.fdb[idx]
        
        obj = cls.__new__(cls, path, *rest, **krest)
        cls.__init__(obj, path, *rest, **krest)
        cls.fdb[idx] = obj
        return obj

class File(metaclass = FileMeta):
    fdb = dict()

    def __init__(self, path):
        # The name corresponding to
        # the target: this can be
        # a path or an abstract name
        self.path = path
                
    def __str__(self):
        return str(self.path)

    def resolve(*args):
        return [File(file) for file in flatten(args)]

class Process(File):
    def __init__(self, path, machine, inputs, extra_args = []):
        super().__init__(path)
        
        # The generator that created this process
        self.machine = machine
        
        # The inputs
        self.inputs = inputs
        
        # The extra arguments taken
        self.extra_args = extra_args
    
    def gen_makefile(self):
        return self.machine.gen_proc_makefile(self)
    
    def gen_ninja(self):
        return self.machine.gen_proc_ninja(self)

class MachineMeta(type):
    def __call__(cls, name, *rest, **krest):
        # If already a file, return it
        if issubclass(type(name), Machine):
            return name
    
        if name in cls.mdb:
            return cls.mdb[name]
        
        obj = cls.__new__(cls, name, *rest, **krest)
        cls.__init__(obj, name, *rest, **krest)
        cls.mdb[name] = obj
        return obj

class Machine(metaclass = MachineMeta):
    mdb = dict()

    def __init__(self, name, exe, mkargs, desc=DEFDESC):
        # The name of the machine
        self.name = name
        
        # Executable used in the process
        self.exe = File(exe)
        
        # The arguments that is used to launch the process
        self.mkargs = wrap_lambda(mkargs)
        
        # The description
        self.desc = wrap_lambda(desc)

    def __call__(self, name, *args, extra_args = []):
        return self.gen(name, *args, extra_args = extra_args)
    
    def gen(self, name, *args, extra_args = []):
        inputs = File.resolve(args)
        path = BUILD / Path.cwd().relative_to(ROOT) / name
        
        return Process(path, self, inputs, extra_args)
    
    def gen_proc_makefile(self, proc):
        inputs = " ".join([str(x) for x in proc.inputs])
        extra_args = " ".join([x for x in proc.extra_args])

        out = "%s: %s\n" % (proc.path, inputs)
        out += "\t@$(%s) %s\n" % (self.name, self.mkargs("$@", inputs, extra_args))
        out += "\t@echo '%s'" % (self.desc("$@", inputs, extra_args))
        
        return out

    def gen_makefile(self):
        return "%s = %s" % (self.name, self.exe)

    def gen_proc_ninja(self, proc):
        inputs = " ".join([str(x) for x in proc.inputs])
        
        out = "build %s: %s %s" % (proc.path, self.name, inputs)
        if proc.extra_args != []:
            extra_args = " ".join([x for x in proc.extra_args])
            out += "\n  extra = %s" % (extra_args)
            
        return out

    def gen_ninja(self):
        out = "rule %s\n" % (self.name)
        
        cmd = "%s %s" % (self.exe, self.mkargs("$out", "$in", "$extra"))
        
        out += "  command = %s\n" % (cmd)
        out += "  description = %s\n" % (self.desc("$out", "$in", cmd))
        return out

class Vec(Machine):
    def __init__(self, name, exe, mkargs, mkout, desc=DEFDESC):
        super().__init__(name, exe, mkargs, desc=desc)
        self.mkout = wrap_lambda(mkout)
    
    def __call__(self, *args, extra_args = []):
        return self.gen(*args, extra_args = extra_args)
    
    def gen(self, *args, extra_args = []):
        args = File.resolve(args)
        extra_args = flatten(extra_args)
        
        procs = []
        for i in args:
            path = BUILD / i.path.parent / self.mkout(i.path)

            procs.append(Process(path, self, [i], extra_args))

        return procs

class CC(Vec):
    def __init__(self, name, exe, mkargs, mkout, mkinc, mkdep=None, depstyle=None, desc=DEFDESC):
        super().__init__(name, exe, mkargs, mkout, desc=desc)
        self.mkinc = mkinc
        self.mkdep = mkdep
        self.depstyle = depstyle
    
    def __call__(self, *args, extra_args = [], include_dirs = []):
        return self.gen(*args, extra_args = extra_args, include_dirs = include_dirs)
    
    def gen(self, *args, extra_args = [], include_dirs = []):
        extra_args = flatten(extra_args)
        include_dirs = File.resolve(include_dirs)

        include_args = [self.mkinc(str(x)) for x in include_dirs]
        extra_args += include_args

        return super().gen(*args, extra_args = extra_args)
        
    def gen_ninja(self):
        out = super().gen_ninja()
        
        if self.mkdep and self.depstyle == "gcc":
            out += "  deps = gcc\n"
            out += "  depfile = %s\n" % (self.mkdep("$out"))
        elif self.mkdep:
            raise Exception("ninja dependencies for selected depstyle is unimplemented")
        
        return out
        
    def gen_proc_makefile(self, proc):
        out = super().gen_proc_makefile(proc)
        out += "\n"

        if self.mkdep and self.depstyle == "gcc":
            out += "-include %s\n" % self.mkdep(proc.path)
        elif self.mkdep:
            raise Exception("makefile dependencies for selected depstyle is unimplemented")
        
        return out

def find_one(names):
    for name in names:
        program = find_program(name, required=False)
        if program:
            return name
    return None

class System:
    def c_compiler(c_compilers=C_COMPILERS.keys()):
        c_compiler = find_one(c_compilers)
        return C_COMPILERS[c_compiler]()

    def c_linker(c_linkers=C_LINKERS.keys()):
        c_linker = find_one(c_linkers)
        return C_LINKERS[c_linker]()

def subdir(dir):
    # Save the previous location
    PWD = Path.cwd()
    
    # Go into subdir
    sub = PWD / dir
    os.chdir(sub)
    
    # Set helper path
    CWD = Path.cwd().relative_to(ROOT)
    exec(open('.build').read())
    
    # Revert the current directory;
    os.chdir(PWD)

subdir(".")

def gen_bld():
    for proc in File.fdb.values():
        if not issubclass(type(proc), Process):
            continue
        proc.path.parent.mkdir(parents=True, exist_ok=True)

def gen_makefile():
    out = ""
    for mach in Machine.mdb.values():
        out += mach.gen_makefile()
        out += "\n"
    
    all = []
    for proc in File.fdb.values():
        if not issubclass(type(proc), Process):
            continue

        out += "\n"
        out += proc.gen_makefile()
        out += "\n"
        all.append(str(proc))
    all = " ".join(all)
    
    out += "\n.PHONY: clean\nclean:\n\trm -f %s" % (all)
    return out
    
def gen_ninja():
    out = ""
    for mach in Machine.mdb.values():
        out += mach.gen_ninja()
        out += "\n"

    for proc in File.fdb.values():
        if not issubclass(type(proc), Process):
            continue
        
        out += proc.gen_ninja()
        out += "\n"
    
    return out

parser = argparse.ArgumentParser(description="cook build system")
parser.add_argument("-G", type=str, metavar="backend", help="Backend to generate for: ninja or makefile")
args = parser.parse_args()

backend = "ninja"
if args.G:
    backend = args.G

gen_bld()
open(ROOT / BUILD / ".gitignore", "w").write("*")
if backend == "ninja":
    open(ROOT / 'build.ninja', 'w').write(gen_ninja())
elif backend == "makefile":
    open(ROOT / 'makefile', 'w').write(gen_makefile())
else:
    print("No such backend %s" % (backend))