123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178 |
- import re
- LINE_OBVIOUSNESS_LIMIT = 4
- LINE_WIDTH=80
- class Problem(Exception):
- pass
- def commented_line(fmt, argument, maxwidth=LINE_WIDTH):
- """
- Return fmt%argument, for use as a commented line. If the line would
- be longer than maxwidth, truncate argument.
- Requires that fmt%"..." will fit into maxwidth characters.
- """
- result = fmt % argument
- if len(result) <= maxwidth:
- return result
- else:
-
-
- ellipsis = "..."
- result = fmt % (argument + ellipsis)
- overrun = len(result) - maxwidth
- truncated_argument = argument[:-overrun] + ellipsis
- result = fmt % truncated_argument
- assert len(result) <= maxwidth
- return result
- def negate(expr):
- """Return a negated version of expr; try to avoid double-negation.
- We usually wrap expressions in parentheses and add a "!".
- >>> negate("A && B")
- '!(A && B)'
- But if we recognize the expression as negated, we can restore it.
- >>> negate(negate("A && B"))
- 'A && B'
- The same applies for defined(FOO).
- >>> negate("defined(FOO)")
- '!defined(FOO)'
- >>> negate(negate("defined(FOO)"))
- 'defined(FOO)'
- Internal parentheses don't confuse us:
- >>> negate("!(FOO) && !(BAR)")
- '!(!(FOO) && !(BAR))'
- """
- expr = expr.strip()
-
- m = re.match(r'^!\s*\(([^\)]*)\)$', expr)
- if m:
- return m.group(1)
-
- m = re.match(r'^(!?)\s*(defined\([^\)]*\))$', expr)
- if m:
- if m.group(1) == "!":
- prefix = ""
- else:
- prefix = "!"
- return prefix + m.group(2)
- return "!(%s)" % expr
- def uncomment(s):
- """
- Remove existing trailing comments from an #else or #endif line.
- """
- s = re.sub(r'//.*','',s)
- s = re.sub(r'/\*.*','',s)
- return s.strip()
- def translate(f_in, f_out):
- """
- Read a file from f_in, and write its annotated version to f_out.
- """
-
-
-
-
-
-
- stack = []
-
- whole_file = []
- cur_level = whole_file
- lineno = 0
- for line in f_in:
- lineno += 1
- m = re.match(r'\s*#\s*(if|ifdef|ifndef|else|endif|elif)\b\s*(.*)',
- line)
- if not m:
-
- f_out.write(line)
- continue
- command,rest = m.groups()
- if command in ("if", "ifdef", "ifndef"):
-
- if command == 'ifdef':
- rest = "defined(%s)"%uncomment(rest)
- elif command == 'ifndef':
- rest = "!defined(%s)"%uncomment(rest)
- elif rest.endswith("\\"):
- rest = rest[:-1]+"..."
- rest = uncomment(rest)
- new_level = [ (command, rest, lineno) ]
- stack.append(cur_level)
- cur_level = new_level
- f_out.write(line)
- elif command in ("else", "elif"):
-
-
- if len(cur_level) == 0 or cur_level[-1][0] == 'else':
- raise Problem("Unexpected #%s on %d"% (command,lineno))
- if (len(cur_level) == 1 and command == 'else' and
- lineno > cur_level[0][2] + LINE_OBVIOUSNESS_LIMIT):
- f_out.write(commented_line("#else /* %s */\n",
- negate(cur_level[0][1])))
- else:
- f_out.write(line)
- cur_level.append((command, rest, lineno))
- else:
-
- assert command == 'endif'
- if len(stack) == 0:
- raise Problem("Unmatched #%s on %s"% (command,lineno))
- if lineno <= cur_level[0][2] + LINE_OBVIOUSNESS_LIMIT:
- f_out.write(line)
- elif len(cur_level) == 1 or (
- len(cur_level) == 2 and cur_level[1][0] == 'else'):
- f_out.write(commented_line("#endif /* %s */\n",
- cur_level[0][1]))
- else:
- f_out.write(commented_line("#endif /* %s || ... */\n",
- cur_level[0][1]))
- cur_level = stack.pop()
- if len(stack) or cur_level != whole_file:
- raise Problem("Missing #endif")
- import sys,os
- for fn in sys.argv[1:]:
- with open(fn+"_OUT", 'w') as output_file:
- translate(open(fn, 'r'), output_file)
- os.rename(fn+"_OUT", fn)
|