summaryrefslogtreecommitdiff
path: root/Cool/compile.py
blob: 9c1940375140b64c682c0c0850b24bb5b332ca8c (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
#!/usr/bin/env python3
import sys
import re
import argparse

TYPE_SPECIFIERS = {
    'int': '%d',
    'int32_t': '%d',
    'short': '%d',
    'long': '%ld',
    'unsigned': '%u',
    'unsigned int': '%u',
    'uint32_t': '%u',
    'size_t': '%zu',
    'float': '%f',
    'double': '%f',
    'char': '%c',
    'char*': '%s',
    'const char*': '%s',
    'char *': '%s',
    'const char *': '%s',
}

def parse_parameters(args_str: str) -> dict:
    param_map = {}
    if not args_str or args_str == 'void':
        return param_map

    params = args_str.split(',')
    for param in params:
        param = param.strip()
        if not param:
            continue
        
        match = re.match(r'^(.*?)\b([A-Za-z0-9_]+)$', param)
        if match:
            type_part = match.group(1).strip()
            var_name = match.group(2).strip()
            
            type_clean = re.sub(r'\s*\*\s*', '*', type_part)
            specifier = TYPE_SPECIFIERS.get(type_clean, '%d')
            param_map[var_name] = (type_clean, specifier)
            
    return param_map

def escape_c_string(text: str) -> str:
    return (text.replace('\\', '\\\\')
                .replace('"', '\\"')
                .replace('\r', '')
                .replace('\n', '\\n'))

def transpile_cool(cool_code: str, filename: str = "<stdin>") -> str:
    lines = cool_code.splitlines(keepends=True)
    c_output = []
    
    cool_func_re = re.compile(r'^\s*COOL\s+void\s+([A-Za-z0-9_]+)\s*\((.*?)\)\s*\{\s*$')
    
    in_cool_func = False
    current_func = ""
    raw_buffer = []
    local_scope = {}

    def flush_raw_buffer():
        nonlocal raw_buffer
        if raw_buffer:
            combined = "".join(raw_buffer)
            if combined:
                escaped = escape_c_string(combined)
                c_output.append(f'    cool_html_raw(COOL_SV("{escaped}"));\n')
            raw_buffer = []

    for line_num, line in enumerate(lines, start=1):
        match = cool_func_re.match(line)
        
        if match and not in_cool_func:
            in_cool_func = True
            current_func, args = match.groups()
            args_str = args.strip() if args.strip() else "void"
            
            local_scope = parse_parameters(args_str)
            c_output.append(f"void {current_func}({args_str}) {{\n")
            continue

        if in_cool_func:
            if line.strip() == "}":
                flush_raw_buffer()
                c_output.append("}\n\n")
                in_cool_func = False
                current_func = ""
                local_scope = {}
                continue

            # Tokenize line into @Component(), { expression }, and plain HTML
            tokens = re.split(r'(@[A-Za-z0-9_]+\s*\([^)]*\)|\{[^{}]+\})', line)

            for token in tokens:
                if not token:
                    continue
                
                # @Component()
                if token.startswith('@') and '(' in token:
                    flush_raw_buffer()
                    call_code = token[1:].strip()
                    c_output.append(f"    {call_code};\n")
                
                # { expression }
                elif token.startswith('{') and token.endswith('}'):
                    flush_raw_buffer()
                    expr = token[1:-1].strip()
                    
                    if expr in local_scope:
                        type_clean, specifier = local_scope[expr]
                        
                        if 'char*' in type_clean:
                            c_output.append(f"    cool_html_txt({expr}, strlen({expr}));\n")
                        else:
                            c_output.append(f'    cool_htmlf_raw("{specifier}", {expr});\n')
                    else:
                        available = ", ".join(f"'{p}'" for p in local_scope.keys()) if local_scope else "none"
                        sys.stderr.write(
                            f"\n[Transpiler Error] {filename}:{line_num}: "
                            f"Expression '{{{expr}}}' in function '{current_func}' does not match any parameter.\n"
                            f"  -> Available parameter(s): {available}\n\n"
                        )
                        sys.exit(1)
                
                # Raw HTML text
                else:
                    raw_buffer.append(token)
        else:
            c_output.append(line)

    return "".join(c_output)

def main():
    parser = argparse.ArgumentParser(description="Transpiles .cool template files to C source code.")
    parser.add_argument("input", help="Input .cool file")
    parser.add_argument("-o", "--output", help="Output .c file")
    args = parser.parse_args()

    with open(args.input, "r", encoding="utf-8") as f:
        cool_code = f.read()

    transpiled_c = transpile_cool(cool_code, filename=args.input)

    if args.output:
        with open(args.output, "w", encoding="utf-8") as f:
            f.write(transpiled_c)
    else:
        sys.stdout.write(transpiled_c)

if __name__ == "__main__":
    main()