Skip to content

Instantly share code, notes, and snippets.

@heiner
Created November 12, 2020 19:34
Show Gist options
  • Select an option

  • Save heiner/2449c21a72715ca535721ab6a1edc162 to your computer and use it in GitHub Desktop.

Select an option

Save heiner/2449c21a72715ca535721ab6a1edc162 to your computer and use it in GitHub Desktop.
import collections
import re
import sys
ifs = ["#ifndef", "#ifdef", "#if"]
SLASHAST = re.compile(r"/\*.*?\*/", re.DOTALL)
DOUBLESLASH = re.compile(r"//.*?\n")
def main():
with open(sys.argv[1]) as f:
stack = collections.deque([])
for i, line in enumerate(f):
if line.startswith("#if"):
for _if in ifs:
if line.startswith(_if):
tag = line[len(_if) :].strip()
tag = re.sub(SLASHAST, "", tag)
tag = re.sub(DOUBLESLASH, "", tag)
stack.append(tag)
break
else:
raise RuntimeError("Unknown if in line %s" % repr(line))
elif line.rstrip() == "#else":
print("#else /* %s */" % stack[-1])
continue
elif line.startswith("#else"):
# print("#else /* %s */" % stack[-1])
if line.lstrip("#else").strip() != "/* %s */" % stack[-1]:
sys.stderr.write(
"Line %i: Not replacing %s with %s after #else\n"
% (i, repr(line.lstrip("#else")), repr(stack[-1]))
)
elif line.startswith("#endif"):
if not line.lstrip("#endif").strip():
print("#endif /* %s */" % stack.pop())
continue
else:
tag = stack.pop()
if line.lstrip("#endif").strip() != "/* %s */" % tag:
sys.stderr.write(
"Line %i: Not replacing %s with %s after #endif\n"
% (i, repr(line.lstrip("#endif")), repr(tag))
)
print(line, end="")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment