| 1 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 2 |
# Copyright (C) 2025-2026 Benjamin Abendroth <[email protected]> |
| 3 |
|
| 4 |
'''Contains code for preprocessing text.''' |
| 5 |
|
| 6 |
|
| 7 |
def preprocess(string, defines): |
| 8 |
'''Simple preprocessor function with #ifdef, #else, and #endif support.''' |
| 9 |
|
| 10 |
defines = set(defines) |
| 11 |
output = [] |
| 12 |
stack = [] # stack of booleans: is this block currently active? |
| 13 |
|
| 14 |
lines = string.splitlines(keepends=True) |
| 15 |
|
| 16 |
for line in lines: |
| 17 |
stripped_line = line.lstrip() |
| 18 |
|
| 19 |
if stripped_line.startswith("#ifdef"): |
| 20 |
define = stripped_line.split()[1] |
| 21 |
active = define in defines |
| 22 |
stack.append(active) |
| 23 |
|
| 24 |
elif stripped_line.startswith("#else"): |
| 25 |
if not stack: |
| 26 |
raise SyntaxError("#else without #ifdef") |
| 27 |
# flip only the current (top of stack) |
| 28 |
stack[-1] = not stack[-1] |
| 29 |
|
| 30 |
elif stripped_line.startswith("#endif"): |
| 31 |
if not stack: |
| 32 |
raise SyntaxError("#endif without #ifdef") |
| 33 |
stack.pop() |
| 34 |
|
| 35 |
else: |
| 36 |
# output only if all enclosing blocks are active |
| 37 |
if not stack or all(stack): |
| 38 |
output.append(line) |
| 39 |
|
| 40 |
if stack: |
| 41 |
raise SyntaxError("Unclosed #ifdef") |
| 42 |
|
| 43 |
return ''.join(output) |
| 44 |
|
| 45 |
|
| 46 |
def _test(): |
| 47 |
string = """\ |
| 48 |
Lorem Ipsum |
| 49 |
#ifdef DEBUG |
| 50 |
This is debug code. |
| 51 |
#ifdef FOO |
| 52 |
This is foo code. |
| 53 |
#else |
| 54 |
This is foo else code. |
| 55 |
#endif |
| 56 |
#endif |
| 57 |
Dolor Sit Amet\ |
| 58 |
""" |
| 59 |
defines = ["DEBUG"] |
| 60 |
result = preprocess(string, defines) |
| 61 |
print(result) |
| 62 |
|
| 63 |
|
| 64 |
if __name__ == '__main__': |
| 65 |
_test() |