Limitations:
* Requires source to be syntactically valid,
* Strange indentation (not one of the standard styles) will confuse it.
- * Will be desperately confused if string literals include \".
* Doesn't even attempt to translate for, switch/case or do/while.
* Doesn't attempt to translate ternary operator.
- * Doesn't yet cope well with multiline closed comments.
* Won't put Python line continuations in multiline conditionals.
* C comma expressions will spuriously turn into Python tuuple constructors,
* We don't translate frexp and modf because their call conventions differ
'id' : r"[a-zA-Z0-9._]+",
'exp' : r"[a-zA-Z0-9._\-+\*/]+",
'type' : r"void|int|bool|char \*|char|short|double|long|float|time_t|FILE \*",
- 'ind': r"^[ \t]*",
}
transformations = (
(r"extern[^;]+;.*\n", r""),
# macros
(r"#define\s+(%(id)s)\s+(.*)\n", r"\1\t= \2\n"),
- (r"#define\s+(%(id)s)\(([^)]*)\)\s+(\(.*)\n", r"def \1(\2):\treturn \3\n"),
+ (r"#define\s+(%(id)s)\(([^)]*)\)\s+(.*\))\n", r"def \1(\2):\treturn \3\n"),
(r"#define\s+(%(id)s)\(([^)]*)\)\s+([^(].*)\n", r"def \1(\2):\t\3\n"),
# function headers
(r"(?:^|\n)(?:static\s+)?(?:%(type)s) +(.*\)) *\n", r"\ndef \1:\n"),
elif state == "opencomment":
if input[i] == "\n":
if debug >= 2:
- print "Open comment ends at %d" % i
+ print "Open comment ends at %d" % (i+1)
boundaries.append(i+1)
state = "text"
boundaries.append(len(input))
regions = []
for i in range(len(boundaries)-1):
regions.append(input[boundaries[i]:boundaries[i+1]])
+ regions = filter(lambda x: x != '', regions)
if debug:
import pprint
pp = pprint.PrettyPrinter(indent=4)
for (s, t) in transformations:
regions[i] = re.sub(s % shorthands, t, regions[i], re.M)
except IndexError:
- sys.stderr.write("ctopy: pathological sting literal at %d.\n" % boundaries[i])
+ sys.stderr.write("ctopy: pathological string literal at %d.\n" % boundaries[i])
raise SystemExit, 1
if debug:
print "Import checks begin"
if importlist:
importlist = "import " + ",".join(importlist) + "\n"
regions.insert(0, importlist)
- # Emit what we got
- return text
+ # Emit what we got. Preverve imports in case this is a .h file
+ return (text, importlist)
if __name__ == "__main__":
import getopt
if (switch == '-d'):
debug = 1
- sys.stdout.write(ctopy(sys.stdin.read(), debug))
+ code = sys.stdin.read()
+ (text, imports) = ctopy(code, debug)
+ sys.stdout.write(text)