import re
import html


def format_type(expr):
    """
    Format type expression for popup
    Set span 'type' for types and 'tyvar' for type variables
    """
    if not expr:
        return expr
    tyname = re.search(r'([a-zA-Z]\w*)|(->|=>|::|\u2192|\u21d2|\u2237)', expr)
    if tyname:
        tyexpr = expr[tyname.start():tyname.end()]
        expr_class = ''
        if tyname.group(1):
            expr_class = 'type' if tyexpr[0].isupper() else 'tyvar'
        elif tyname.group(2):
            expr_class = 'operator'
        decorated = '<span class="{0}">{1}</span>'.format(expr_class, html.escape(tyexpr, quote=False))
        return html.escape(expr[0:tyname.start()], quote=False) + decorated + format_type(expr[tyname.end():])
    else:
        return html.escape(expr, quote=False)