|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import sys |
| 4 | +import argparse |
| 5 | +import pathlib |
| 6 | +import re |
| 7 | +from dataclasses import dataclass |
| 8 | + |
| 9 | +@dataclass |
| 10 | +class Define: |
| 11 | + value: int |
| 12 | + location: str |
| 13 | + |
| 14 | +@dataclass |
| 15 | +class If: |
| 16 | + value: int |
| 17 | + location: str |
| 18 | + |
| 19 | +@dataclass |
| 20 | +class Else: |
| 21 | + value: int |
| 22 | + location: str |
| 23 | + |
| 24 | +def any_zero(ifs_elses): |
| 25 | + return any([if_else.value == 0 for if_else in ifs_elses]) |
| 26 | + |
| 27 | +def parse_file(input_path, defines, ifs_elses): |
| 28 | + output_lines = [] |
| 29 | + |
| 30 | + with input_path.open(encoding='utf-8') as input_file: |
| 31 | + for i, line in enumerate(input_file.readlines()): |
| 32 | + m = re.match(r'^[/\s]*//\s*#\s*(.*)$', line.strip()) |
| 33 | + |
| 34 | + if m != None: |
| 35 | + directive = m.group(1) |
| 36 | + m = re.match(r'^(include |define |undef |ifdef |if |else|endif)\s*(.*)$', directive) |
| 37 | + |
| 38 | + if m == None: |
| 39 | + raise Exception(f'Malformed directive at {input_path}:{i + 1}: {line.rstrip('\r\n')}') |
| 40 | + |
| 41 | + verb = m.group(1).strip() |
| 42 | + arguments = m.group(2) |
| 43 | + |
| 44 | + if verb == 'include': |
| 45 | + m = re.match(r'^(?:"([^"]+)"|\'([^\']+)\')$', arguments) |
| 46 | + |
| 47 | + if m == None: |
| 48 | + raise Exception(f'Malformed path in #include directive at {input_path}:{i + 1}: {line.rstrip('\r\n')}') |
| 49 | + |
| 50 | + include_path = input_path.parent / pathlib.Path(m.group(1)) |
| 51 | + |
| 52 | + if not any_zero(ifs_elses): |
| 53 | + if not include_path.exists(): |
| 54 | + raise Exception(f'File in #include directive at {input_path}:{i + 1} is missing: {include_path}') |
| 55 | + |
| 56 | + parse_file(include_path, defines, ifs_elses) |
| 57 | + elif verb == 'define': |
| 58 | + m = re.match(r'^([A-Za-z_-][A-Za-z0-9_-]*)\s+(0|1)$', arguments) |
| 59 | + |
| 60 | + if m == None: |
| 61 | + raise Exception(f'Malformed arguments in #define directive at {input_path}:{i + 1}: {line.rstrip('\r\n')}') |
| 62 | + |
| 63 | + if not any_zero(ifs_elses): |
| 64 | + symbol = m.group(1) |
| 65 | + value = int(m.group(2)) |
| 66 | + define = defines.get(symbol) |
| 67 | + |
| 68 | + if define != None: |
| 69 | + raise Exception(f'Symbol {symbol} in #define directive at {input_path}:{i + 1} is already defined as {define.value} at {define.location}: {line.rstrip('\r\n')}') |
| 70 | + else: |
| 71 | + defines[symbol] = Define(value, f'{input_path}:{i + 1}') |
| 72 | + elif verb == 'undef': |
| 73 | + m = re.match(r'^([A-Za-z_-][A-Za-z0-9_-]*)$', arguments) |
| 74 | + |
| 75 | + if m == None: |
| 76 | + raise Exception(f'Malformed arguments in #undef directive at {input_path}:{i + 1}: {line.rstrip('\r\n')}') |
| 77 | + |
| 78 | + if not any_zero(ifs_elses): |
| 79 | + symbol = m.group(1) |
| 80 | + define = defines.get(symbol) |
| 81 | + |
| 82 | + if define == None: |
| 83 | + raise Exception(f'Symbol {symbol} in #undef directive at {input_path}:{i + 1} is not defined: {line.rstrip('\r\n')}') |
| 84 | + |
| 85 | + line = line.rstrip() + f' [defined at {define.location}]\n' |
| 86 | + defines.pop(symbol) |
| 87 | + elif verb == 'ifdef': |
| 88 | + m = re.match(r'^([A-Za-z_-][A-Za-z0-9_-]*)$', arguments) |
| 89 | + |
| 90 | + if m == None: |
| 91 | + raise Exception(f'Malformed arguments in #ifdef directive at {input_path}:{i + 1}: {line.rstrip('\r\n')}') |
| 92 | + |
| 93 | + symbol = m.group(1) |
| 94 | + value = None |
| 95 | + |
| 96 | + if not any_zero(ifs_elses): |
| 97 | + define = defines.get(symbol) |
| 98 | + |
| 99 | + if define != None: |
| 100 | + value = 1 |
| 101 | + line = line.rstrip() + f' [defined as {define.value} at {define.location}]\n' |
| 102 | + else: |
| 103 | + value = 0 |
| 104 | + line = line.rstrip() + f' [not defined]\n' |
| 105 | + |
| 106 | + ifs_elses.append(If(value, f'{input_path}:{i + 1}')) |
| 107 | + elif verb == 'if': |
| 108 | + m = re.match(r'^(1|0|[A-Za-z_-][A-Za-z0-9_-]*)$', arguments) |
| 109 | + |
| 110 | + if m == None: |
| 111 | + raise Exception(f'Malformed arguments in #if directive at {input_path}:{i + 1}: {line.rstrip('\r\n')}') |
| 112 | + |
| 113 | + value_or_symbol = m.group(1) |
| 114 | + value = None |
| 115 | + |
| 116 | + if not any_zero(ifs_elses): |
| 117 | + if value_or_symbol in ['1', '0']: |
| 118 | + value = int(value_or_symbol) |
| 119 | + else: |
| 120 | + symbol = value_or_symbol |
| 121 | + define = defines.get(symbol) |
| 122 | + |
| 123 | + if define == None: |
| 124 | + raise Exception(f'Symbol {symbol} in #if directive at {input_path}:{i + 1} is not defined: {line.rstrip('\r\n')}') |
| 125 | + |
| 126 | + value = define.value |
| 127 | + line = line.rstrip() + f' [defined as {value} at {define.location}]\n' |
| 128 | + |
| 129 | + ifs_elses.append(If(value, f'{input_path}:{i + 1}')) |
| 130 | + elif verb == 'else': |
| 131 | + if len(arguments) > 0: |
| 132 | + raise Exception(f'Unexpected arguments in #else directive at {input_path}:{i + 1}: {line.rstrip('\r\n')}') |
| 133 | + |
| 134 | + if len(ifs_elses) == 0: |
| 135 | + raise Exception(f'Missing #if directive for #else directive at {input_path}:{i + 1}: {line.rstrip('\r\n')}') |
| 136 | + |
| 137 | + if_else = ifs_elses.pop() |
| 138 | + |
| 139 | + if isinstance(if_else, Else): |
| 140 | + raise Exception(f'Duplicate #else directive at {input_path}:{i + 1}: {line.rstrip('\r\n')}') |
| 141 | + |
| 142 | + ifs_elses.append(Else(1 - if_else.value, f'{input_path}:{i + 1}')) |
| 143 | + elif verb == 'endif': |
| 144 | + if len(arguments) > 0: |
| 145 | + raise Exception(f'Unexpected arguments in #endif directive at {input_path}:{i + 1}: {line.rstrip('\r\n')}') |
| 146 | + |
| 147 | + if len(ifs_elses) == 0: |
| 148 | + raise Exception(f'Missing #if directive for #endif directive at {input_path}:{i + 1}: {line.rstrip('\r\n')}') |
| 149 | + |
| 150 | + ifs_elses.pop() |
| 151 | + |
| 152 | + if any_zero(ifs_elses) and not line.lstrip().startswith('//'): |
| 153 | + line = '//' + line |
| 154 | + |
| 155 | + output_lines.append(line) |
| 156 | + |
| 157 | + return output_lines |
| 158 | + |
| 159 | +def tfpp(input_path, output_path, overwrite=False): |
| 160 | + input_path = pathlib.Path(input_path) |
| 161 | + output_path = pathlib.Path(output_path) |
| 162 | + |
| 163 | + if not input_path.exists(): |
| 164 | + raise Exception(f"Input file {input_path} is missing") |
| 165 | + |
| 166 | + if output_path.exists() and not overwrite: |
| 167 | + raise Exception(f"Output file {output_path} already exists") |
| 168 | + |
| 169 | + if input_path == output_path: |
| 170 | + raise Exception(f"Input file {input_path} and output file {output_path} are the same") |
| 171 | + |
| 172 | + defines = {} |
| 173 | + ifs_elses = [] |
| 174 | + output_lines = parse_file(input_path, defines, ifs_elses) |
| 175 | + |
| 176 | + if len(ifs_elses) > 0: |
| 177 | + raise Exception(f'Missing #endif directive for #{"if" if isinstance(ifs_elses[0], If) else "else"} directive at {ifs_elses[0].location}') |
| 178 | + |
| 179 | + output_path.parent.mkdir(parents=True, exist_ok=True) |
| 180 | + output_path_tmp = output_path.with_suffix('.tfpptmp') |
| 181 | + |
| 182 | + with output_path_tmp.open(mode='w', encoding='utf-8') as output_file: |
| 183 | + output_file.writelines(output_lines) |
| 184 | + |
| 185 | + output_path_tmp.replace(output_path) |
| 186 | + |
| 187 | +def main(): |
| 188 | + parser = argparse.ArgumentParser() |
| 189 | + parser.add_argument('input_path') |
| 190 | + parser.add_argument('output_path') |
| 191 | + parser.add_argument('--overwrite', action='store_true') |
| 192 | + |
| 193 | + args = parser.parse_args() |
| 194 | + |
| 195 | + tfpp(input_path=args.input_path, output_path=args.output_path, overwrite=args.overwrite) |
| 196 | + |
| 197 | +if __name__ == '__main__': |
| 198 | + try: |
| 199 | + main() |
| 200 | + except Exception as e: |
| 201 | + print(f'Error: {e}') |
| 202 | + sys.exit(1) |
0 commit comments