# coding: utf8
import re
import pycparser.c_generator


def parse_constant(node):
    if isinstance(node, pycparser.c_ast.Constant):
        return node.value
    elif isinstance(node, pycparser.c_ast.UnaryOp) and node.op == '-':
        return '-' + parse_constant(node.expr)
    else:
        raise TypeError(node)


class Visitor(pycparser.c_ast.NodeVisitor):
    def visit_Enum(self, node):
        value = 0
        for enumerator in node.values.enumerators:
            if enumerator.value is not None:
                value_string = parse_constant(enumerator.value)
                value = int(value_string, 0)
            else:
                value_string = str(value)
            assert enumerator.name.startswith('CAIRO_')  # len('CAIRO_') == 6
            print('%s = %s' % (enumerator.name[6:], value_string))
            value += 1
        print('')


def generate(include_dir):
    # Remove comments, preprocessor instructions and macros.
    source = re.sub(
        '/\*.*?\*/'
        '|CAIRO_(BEGIN|END)_DECLS'
        '|cairo_public '
        r'|^\s*#.*?[^\\]\n',
        '',
        ''.join(open('%s/cairo%s.h' % (include_dir, suffix), 'r').read()
                for suffix in ['', '-pdf', '-ps', '-svg']),
        flags=re.DOTALL | re.MULTILINE)
    print('# Generated by mkconstants.py\n')
    ast = pycparser.CParser().parse(source)
    Visitor().visit(ast)
    source = pycparser.c_generator.CGenerator().visit(ast)
    print('_CAIRO_HEADERS = r"""\n%s\n"""' % source.strip())


if __name__ == '__main__':
    generate('/usr/include/cairo')
