"""
open/DurusWorks/qpy/translate.py

"""
import re
import sys
import symbol

_annotation_re = re.compile(
    r"^(?P<indent>[ \t]*)def(?:[ \t]+)"
    r"(?P<name>[a-zA-Z_][a-zA-Z_0-9]*)"
    r"(?:[ \t]*:[ \t]*)(?P<type>xml|str)(?:[ \t]*)"
    r"(?:[ \t]*[\(\\])",
    re.MULTILINE|re.VERBOSE)

_template_re = re.compile(
    r"^(?P<indent>[ \t]*) def (?:[ \t]+)"
    r" (?P<name>[a-zA-Z_][a-zA-Z_0-9]*)"
    r" (?:[ \t]*) \[(?P<type>plain|html)\] (?:[ \t]*)"
    r" (?:[ \t]*[\(\\])",
    re.MULTILINE|re.VERBOSE)

def translate_tokens(buf):
    """
    def f:xml( ... )  -> def f__xml_template__(...):
    def f:str( ... )  -> def f__str_template__(...):

    and, for backward compatibility,

    def foo [html] (...): -> def foo__xml_template__(...):
    def foo [plain] (...): -> def foo__str_template__(...):
    """
    def replacement(match):
        if match.group('type') in ('xml', 'html'):
            template_type = 'xml'
        elif match.group('type') in ('str', 'plain'):
            template_type = 'str'
        return '%sdef %s__%s_template__(' % (match.group('indent'),
                                 match.group('name'),
                                 template_type)
    translated = _annotation_re.sub(replacement, buf)
    translated = _template_re.sub(replacement, translated)
    return translated

