pythonize_constants.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # Copyright (C) 2013 Internet Systems Consortium.
  2. #
  3. # Permission to use, copy, modify, and distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM
  8. # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL
  9. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  10. # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT,
  11. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  12. # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  13. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  14. # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  15. '''
  16. This script takes a C++ file with constants and converts it to a python
  17. module. However, the syntax it parses is very limited (it doesn't understand
  18. C++ at all, it just looks for lines containing the equal sign and strips
  19. what it thinks might be type).
  20. The purpose is to keep the same values of constants in C++ and python. This
  21. saves the work of keeping the constants in sync manually and is less error
  22. prone.
  23. '''
  24. import sys
  25. import re
  26. if len(sys.argv) != 3:
  27. sys.stderr.write("Usage: python3 ./pythonize_constants.py input.cc output.py\n")
  28. sys.exit(1)
  29. [filename_in, filename_out] = sys.argv[1:3]
  30. # Ignore preprocessor, namespaces and the ends of namespaces.
  31. ignore = re.compile('^(#|namespace|})')
  32. comment = re.compile('^//(.*)')
  33. constant = re.compile('^[a-zA-Z].*?([a-zA-Z_0-9]+\\s*=.*);')
  34. with open(filename_in) as file_in, open(filename_out, "w") as file_out:
  35. file_out.write("# This file is generated from " + filename_in + "\n" +
  36. "# by the pythonize_constants.py script.\n" +
  37. "# Do not edit, all changes will be lost.\n\n")
  38. for line in file_in:
  39. if ignore.match(line):
  40. continue
  41. # Mangle comments to be python-like
  42. line = comment.sub('#\\1', line)
  43. # Extract the constant.
  44. # TODO: We may want to do something with the true vs. True and
  45. # NULL vs. None and such. Left out for now, since none are in
  46. # the input file currently.
  47. line = constant.sub('\\1', line)
  48. file_out.write(line)