Last active
March 8, 2016 17:36
-
-
Save janbraiins/23def819ee6285eebc97 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
import re | |
fn = sys.argv[1] | |
with open(fn, 'rt') as f: | |
lines = [ l.strip() for l in f.readlines() ] | |
blocks = [] | |
output = [] | |
class DefineBlock(object): | |
def __init__(self, define_line): | |
self.qstrs = [] | |
self.define_line = define_line | |
def append(self, qstr): | |
self.qstrs.append(qstr) | |
def is_empty(self): | |
len(self.qstrs) == 0 | |
def get_output(self): | |
return [self.define_line] + self.qstrs | |
def __str__(self): | |
return "Define: '%s', QSTRS: %s" % (self.define_line, | |
self.qstrs) | |
count = 0 | |
last_ifdef_idx = 0 | |
for l in lines: | |
if l.startswith('#if'): | |
b = DefineBlock(l) | |
last_ifdef_idx = len(blocks) | |
blocks.append(b) | |
print("Appending #if block: %s" % b) | |
elif l.startswith('#endif'): | |
empty_ifdef_removed = False | |
while (len(blocks) > last_ifdef_idx): | |
b = blocks.pop(last_ifdef_idx) | |
print("Removing block %s" % b) | |
empty_ifdef_removed = True | |
if empty_ifdef_removed is False: | |
output.append(l) | |
elif l.startswith('#else') or l.startswith('#elif'): | |
b = DefineBlock(l) | |
blocks.append(b) | |
print("Appending #else/#elif block: %s" % b) | |
else: | |
qstr_list = [] | |
for q in re.findall(r'MP_QSTR_[_a-zA-Z0-9]+', l): | |
q = q.replace('MP_QSTR_', 'Q(') + ')' | |
print("Appending %s" % q) | |
qstr_list.append(q) | |
if len(qstr_list) > 0: | |
while len(blocks) > 0: | |
output.extend(blocks.pop(0).get_output()) | |
output.extend(qstr_list) | |
count += 1 | |
if len(blocks) != 0: | |
sys.stderr.write("Syntax error, probably unterminated blocks: %s\n" % blocks) | |
sys.exit(1) | |
print('\n'.join(output)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment