Created
January 30, 2013 13:45
-
-
Save zeha/4673411 to your computer and use it in GitHub Desktop.
parser for a tiny subset of the C preprocessor lang
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
def parseheader(headerstream, defined_constants): | |
depth = 0 | |
ignoring = False | |
for line in headerstream: | |
line = line.strip() | |
if not line.startswith('#'): | |
continue | |
if line.startswith('#endif'): | |
depth -= 1 | |
ignoring = False | |
elif line.startswith('#else'): | |
ignoring = not ignoring | |
elif not ignoring: | |
splitted = line.split(' ') | |
if line.startswith('#define'): | |
constant = splitted[1] | |
if len(splitted) > 2: | |
value = splitted[2] | |
else: | |
value = True | |
defined_constants[constant] = value | |
elif line.startswith('#ifdef'): | |
depth += 1 | |
constant = line.split(' ')[1] | |
if constant in defined_constants: | |
ignoring = False | |
else: | |
ignoring = True | |
elif line.startswith('#ifndef'): | |
depth += 1 | |
constant = line.split(' ')[1] | |
if constant in defined_constants: | |
ignoring = True | |
else: | |
ignoring = False | |
elif line.startswith('#undef'): | |
constant = splitted[1] | |
del defined_constants[constant] | |
else: | |
raise Exception('Unknown preprocessor command: %s' % line) | |
return defined_constants | |
if __name__ == "__main__": | |
testdoc = """ | |
#ifndef PROJECT_H | |
#define PROJECT_H | |
#define PROJECT_NAME "project" | |
#ifdef BASELINE | |
#define REVISION 0 | |
#else | |
#define REVISION 7 | |
#endif | |
#endif | |
""" | |
from cStringIO import StringIO | |
print(repr(parseheader(StringIO(testdoc), {}))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment