summaryrefslogtreecommitdiff
path: root/codegen/cgen.py
blob: 0685a6d9c4a888108b7a0c5273ced4d8a3230e9d (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
""" C header generation """
__license__ = 'GPL-3.0-only'

from .types import Variable, Function, Struct

def variable_str(var: Variable):
    return f'{var.typedef}{"" if var.typedef.endswith("*") else " "}{var.name};'

def function_str(func: Function):
    args = '' if func.args is None else ', '.join(
            f'{T+" " if T is not None else ""}{param}'
            for param, T in func.args.items())
    return f'{func.result} {func.name}({args});'

def function_ptr_str(func: Function):
    args = '' if func.args is None else ', '.join(
            f'{T+" " if T is not None else ""}{param}'
            for param, T in func.args.items())
    return f'{func.result} (*{func.name})({args});'

def struct_str(struct: Struct):
    members = '\n'.join([ f'  {nested_object_str(it)}' for it in struct.members ])
    return f"""typedef struct {{
{members}
}} {struct.name};"""

def nested_object_str(obj):
    if isinstance(obj, Variable):
        return variable_str(obj)
    if isinstance(obj, Function):
        return function_ptr_str(obj)
    return None

def as_str(obj):
    if isinstance(obj, Variable):
        return variable_str(obj)
    if isinstance(obj, Function):
        return function_str(obj)
    if isinstance(obj, Struct):
        return struct_str(obj)
    return None