PageRenderTime 61ms CodeModel.GetById 31ms RepoModel.GetById 0ms app.codeStats 0ms

/qpy/translate.py

https://bitbucket.org/pfw/durusworks
Python | 44 lines | 27 code | 4 blank | 13 comment | 2 complexity | 33dc1e97296f42b6c5e02644bc5f0a0d MD5 | raw file
  1. """
  2. open/DurusWorks/qpy/translate.py
  3. """
  4. import re
  5. import sys
  6. import symbol
  7. _annotation_re = re.compile(
  8. r"^(?P<indent>[ \t]*)def(?:[ \t]+)"
  9. r"(?P<name>[a-zA-Z_][a-zA-Z_0-9]*)"
  10. r"(?:[ \t]*:[ \t]*)(?P<type>xml|str)(?:[ \t]*)"
  11. r"(?:[ \t]*[\(\\])",
  12. re.MULTILINE|re.VERBOSE)
  13. _template_re = re.compile(
  14. r"^(?P<indent>[ \t]*) def (?:[ \t]+)"
  15. r" (?P<name>[a-zA-Z_][a-zA-Z_0-9]*)"
  16. r" (?:[ \t]*) \[(?P<type>plain|html)\] (?:[ \t]*)"
  17. r" (?:[ \t]*[\(\\])",
  18. re.MULTILINE|re.VERBOSE)
  19. def translate_tokens(buf):
  20. """
  21. def f:xml( ... ) -> def f__xml_template__(...):
  22. def f:str( ... ) -> def f__str_template__(...):
  23. and, for backward compatibility,
  24. def foo [html] (...): -> def foo__xml_template__(...):
  25. def foo [plain] (...): -> def foo__str_template__(...):
  26. """
  27. def replacement(match):
  28. if match.group('type') in ('xml', 'html'):
  29. template_type = 'xml'
  30. elif match.group('type') in ('str', 'plain'):
  31. template_type = 'str'
  32. return '%sdef %s__%s_template__(' % (match.group('indent'),
  33. match.group('name'),
  34. template_type)
  35. translated = _annotation_re.sub(replacement, str(buf))
  36. translated = _template_re.sub(replacement, translated)
  37. return translated