aboutsummaryrefslogtreecommitdiff
path: root/lib/c.py
blob: 4f0ae2980216ff32b97b517991aa32e548f75142 (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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#! /bin/python3
from __future__ import annotations

import os
import sys

from abc    import ABC, abstractmethod
from enum   import Enum
from typing import List

# ------------------------------------------------------------------------
# String buffer

level  = 0
buffer = ""

def emit(s: str):
    global buffer
    buffer += s

def emitln(n=1):
    global buffer
    buffer += "\n"*n + ("    " * level)

def enter_scope():
    global level
    emit("{")
    level += 1
    emitln()

def exits_scope():
    global level
    level -= 1
    emitln()
    emit("}")

# ------------------------------------------------------------------------
# Simple C AST
# TODO: Type checking

# Abstract class everything will derive from
# All AST nodes will have an "emit" function that outputs formatted C code
class Emitter(ABC):
    @abstractmethod
    def emit(self):
        pass

# ------------------------------------------
# Representation of a C type
class TypeKind(Enum):
    Void    = "void"
    Error   = "error"

    Int     = "int"
    Int32   = "int32"
    Int64   = "int64"

    # vectorized variants
    Int32x4 = "__mm128i"
    Int32x8 = "__mm256i"
    Int64x2 = "__mm128i"
    Int64x4 = "__mm256i"

    Float32 = "float"
    Float64 = "double"

    # vectorized variants
    Float32x4 = "__m128"
    Float32x8 = "__mm256"
    Float64x2 = "__mm128d"
    Float64x4 = "__mm256d"

    Pointer   = "pointer"
    Struct    = "struct"
    Enum      = "enum"
    Union     = "union"

class Type(Emitter):
    def emit(self):
        pass

    def emitspec(self, var):
        pass

class Base(Type):
    def __init__(self, name: str):
        self.name = name

    def emit(self):
        emit(self.name)

    def emitspec(self, ident):
        emit(f"{ident}")

# Machine primitive types
Void      = Base("void")
Error     = Base("error")

Int       = Base("int")
Int32     = Base("int32")
Int64     = Base("int64")
Int32x4   = Base("__mm128i")
Int32x8   = Base("__mm256i")
Int64x2   = Base("__mm128i")
Int64x4   = Base("__mm256i")

Float32   = Base("float")
Float64   = Base("double")
Float32x4 = Base("__m128")
Float32x8 = Base("__mm256")
Float64x2 = Base("__m128d")
Float64x4 = Base("__mm256d")

class Ptr(Type):
    def __init__(self, to: Type):
        self.to = to

    def emit(self):
        self.to.emit()

    def emitspec(self, ident):
        emit("*")
        self.to.emitspec(ident)

class Array(Type):
    def __init__(self, base: Type, len: int):
        self.base = base
        self.len  = len

    def emit(self):
        self.base.emit()

    def emitspec(self, ident):
        self.base.emitspec(ident)
        emit(f"[{self.len}]")

# TODO: Typedefs...

# ------------------------------------------
# C expressions
class Expr(Emitter):
    def emit():
        pass

# Binary operators
class BinOp(Expr):
    def __init__(self, left: Expr, right: Expr):
        self.l = left
        self.r = right

    def emit(self):
        pass

# TODO: check types if they are vectorized and emit correct intrinsic
class Add(BinOp):
    def emit(self):
        self.l.emit()
        emit(f" + ")
        self.r.emit()

class Sub(BinOp):
    def emit(self):
        self.l.emit()
        emit(f" - ")
        self.r.emit()

class Mul(BinOp):
    def emit(self):
        self.l.emit()
        emit(f" * ")
        self.r.emit()

class Div(BinOp):
    def emit(self):
        self.l.emit()
        emit(f" / ")
        self.r.emit()

class Gt(BinOp):
    def emit(self):
        self.l.emit()
        emit(f" > ")
        self.r.emit()

class Lt(BinOp):
    def emit(self):
        self.l.emit()
        emit(f" < ")
        self.r.emit()

class Ge(BinOp):
    def emit(self):
        self.l.emit()
        emit(f" >= ")
        self.r.emit()

class Le(BinOp):
    def emit(self):
        self.l.emit()
        emit(f" <= ")
        self.r.emit()

class Eq(BinOp):
    def emit(self):
        self.l.emit()
        emit(f" == ")
        self.r.emit()

# Assignment (stores)
class Assign(Expr):
    def __init__(self, lhs: Expr, rhs: Expr):
        self.lhs = lhs
        self.rhs = rhs

class Mv(Assign):
    def emit(self):
        self.lhs.emit()
        emit(f" = ")
        self.rhs.emit()

class AddMv(Assign):
    def emit(self):
        self.lhs.emit()
        emit(f" += ")
        self.rhs.emit()

class SubMv(Assign):
    def emit(self):
        self.lhs.emit()
        emit(f" -= ")
        self.rhs.emit()

class MulMv(Assign):
    def emit(self):
        self.lhs.emit()
        emit(f" *= ")
        self.rhs.emit()

class DivMv(Assign):
    def emit(self):
        self.lhs.emit()
        emit(f" /= ")
        self.rhs.emit()

class Comma(Expr):
    def __init__(self, x: Expr, next: Expr):
        self.expr = (x, next)

    def emit(self):
        self.expr[0].emit()
        emit(", ")
        self.expr[1].emit()

# Common assignments are kept globally
# C statements

class Stmt(Emitter):
    def emit(self):
        emit(";")

class Empty(Stmt):
    def __init__(self):
        pass
    def emit(self):
        super(Empty, self).emit()

class Block(Stmt):
    def __init__(self, stmts: List[Stmt]):
        self.stmts = stmts

    def emit(self):
        enter_scope()
        for stmt in self.stmts:
            stmt.emit()
        exits_scope()
        super(Block, self).emit()

class For(Stmt):
    def __init__(self, init: Expr, cond: Expr, step: Expr, body: Stmt):
        self.init = init
        self.cond = cond
        self.step = step
        self.body = body

    def emit(self):
        emit("for (")
        self.init.emit()
        emit(";")
        self.cond.emit()
        emit(";")
        self.step.emit()
        emit(")")

        self.body.emit()
        super(For, self).emit()

class Return(Stmt):
    def __init__(self, val: Expr):
        self.val = val

    def emit(self):
        emitln()
        emit("return ")
        self.val.emit()
        super(Return, self).emit()

class StmtExpr(Stmt):
    def __init__(self, x: Expr):
        self.x = x

    def emit(self):
        self.x.emit()
        super(StmtExpr, self).emit()

class Mem(Enum):
    Auto     = ""
    Static   = "static"
    Register = "register"
    Typedef  = "typedef"
    External = "extern"

class Decl(Emitter):
    def __init__(self):
        pass

    def emit(self):
        pass

class Func(Decl):
    def __init__(self, ident: str, ret: Expr = Void, params: List[Param] = [], vars: List[Var | List[Var]] = [], body: List[Stmt] = []):
        self.ident  = ident
        self.ret    = ret
        self.params = params
        self.vars   = vars
        self.stmts  = body

    def emit(self):
        self.ret.emit()
        emitln()
        emit(self.ident)
        emit("(")
        for i, p in enumerate(self.params):
            p.emittype()
            emit(" ")
            p.emitspec()
            if i < len(self.params) - 1:
                emit(", ")
        emit(")\n")

        enter_scope()

        for var in self.vars:
            if isinstance(var, list):
                v = var[0]
                v.emittype()
                emit(" ")
                v.emitspec()
                for v in var[1:]:
                    emit(", ")
                    v.emitspec()
            else:
                var.emittype()
                emit(" ")
                var.emitspec()

            emit(";")
            emitln()

        emitln()
        for stmt in self.stmts:
            stmt.emit()

        exits_scope()

    def declare(self, var: Var, *vars: List[Var]):
        self.vars.append(var)
        self.vars.extend(vars)

    def instruct(self, stmt: Stmt | Expr, *args: List[Stmt | Expr]):
        def push(n):
            if isinstance(n, Stmt):
                self.stmts.append(n)
            elif isinstance(n, Expr):
                self.stmts.append(StmtExpr(n))
            else:
                raise TypeError("unrecognized type for function")

        push(stmt)
        for arg in args:
            push(arg)

class Var(Decl):
    def __init__(self, type: Type, name: str, storage: Mem = Mem.Auto):
        self.name    = name
        self.type    = type
        self.storage = storage

    def emit(self):
        emit(f"{self.name}")

    def emittype(self):
        if self.storage != Mem.Auto:
            emit(self.storage.value)
            emit(" ")
        self.type.emit()

    def emitspec(self):
        self.type.emitspec(self.name)

class Param(Var):
    def __init__(self, type: Type, name: str):
        return super(Param, self).__init__(type, name, mem.Auto)

# ------------------------------------------------------------------------
# AST modification functions