#!/usr/bin/env python3"""Minimal unifdef: resolves #if/#ifdef/#ifndef/#elif/#else/#endif with a fixed set of defines.Unknown identifiers evaluate to 0 (C semantics). Lines of kept branches are emitted unchanged.Usage: unifdef.py in.c > out.c"""import re, sysDEFS = { 'NDEBUG': 1, 'ALIS_SDL_VER': 2, 'ALIS_CONV_INPLACE': 1, 'ALIS_USE_THREADS': 0, '__GNUC__': 1, '__has_include': 0, 'VM_IGNORE_ERRORS': 0, '__BYTE_ORDER__': 1234, '__ORDER_LITTLE_ENDIAN__': 1234, '__ORDER_BIG_ENDIAN__': 4321, 'ALIS_SND_INTERPOLATE_TYPE': 0,}def evaluate(expr): expr = expr.split('//')[0] expr = re.sub(r'/\*.*?\*/', '', expr) expr = re.sub(r'defined\s*\(\s*(\w+)\s*\)', lambda m: '1' if m.group(1) in DEFS else '0', expr) expr = re.sub(r'defined\s+(\w+)', lambda m: '1' if m.group(1) in DEFS else '0', expr) expr = re.sub(r'\b([A-Za-z_]\w*)\b(\s*\()?', lambda m: m.group(0) if m.group(2) else str(DEFS.get(m.group(1), 0)), expr) expr = expr.replace('&&', ' and ').replace('||', ' or ') expr = re.sub(r'!(?!=)', ' not ', expr) expr = re.sub(r'(\d+)[uUlL]+', r'\1', expr) try: return bool(eval(expr, {}, {})) except Exception: return None # unknown: keep the directive and both branchesdef main(path): out = [] # stack of (mode, taken, active_parent) ; mode: 'resolved' or 'kept' stack = [] def active(): return all(s['emit'] for s in stack) for line in open(path, encoding='utf-8', errors='replace'): m = re.match(r'\s*#\s*(ifdef|ifndef|if|elif|else|endif)\b(.*)', line) if not m: if active(): out.append(line) continue d, rest = m.group(1), m.group(2).strip() if d in ('if', 'ifdef', 'ifndef'): if d == 'ifdef': v = rest.split()[0] in DEFS elif d == 'ifndef': name = rest.split()[0] v = None if name.endswith('_H') or name in ('max', 'min') else (name not in DEFS) else: v = evaluate(rest) if v is None: stack.append({'kept': True, 'taken': False, 'emit': True}) if active(): out.append(line) else: stack.append({'kept': False, 'taken': v, 'emit': v}) elif d == 'elif': s = stack[-1] if s['kept']: if all(x['emit'] for x in stack[:-1]): out.append(line) continue if s['taken']: s['emit'] = False else: v = evaluate(rest) s['taken'] = s['emit'] = bool(v) elif d == 'else': s = stack[-1] if s['kept']: if all(x['emit'] for x in stack[:-1]): out.append(line) continue s['emit'] = not s['taken'] s['taken'] = True elif d == 'endif': s = stack.pop() if s['kept'] and active(): out.append(line) sys.stdout.write(''.join(out))main(sys.argv[1])