Debian Codegraph @

utils/mkconstants.py

raw
1 import os
2 import re
3 import sys
4 import textwrap
5
6 import pycparser.c_generator
7
8
9 def parse_constant(node):
10 if isinstance(node, pycparser.c_ast.Constant):
11 return node.value
12 elif isinstance(node, pycparser.c_ast.UnaryOp) and node.op == '-':
13 return '-' + parse_constant(node.expr)
14 else:
15 raise TypeError(node)
16
17
18 class PrintEnumsVisitor(pycparser.c_ast.NodeVisitor):
19 def visit_Decl(self, node): # noqa: N802
20 if node.name and node.name.startswith('CAIRO_'): # len('CAIRO_') == 6
21 if node.init.type == 'string':
22 print('%s = b%s' % (node.name[6:], node.init.value))
23 else:
24 print('%s = %s' % (node.name[6:], node.init.value))
25 print('')
26
27 def visit_Enum(self, node): # noqa: N802
28 value = 0
29 for enumerator in node.values.enumerators:
30 if enumerator.value is not None:
31 value_string = parse_constant(enumerator.value)
32 value = int(value_string, 0)
33 else:
34 value_string = str(value)
35 assert enumerator.name.startswith('CAIRO_') # len('CAIRO_') == 6
36 print('%s = %s' % (enumerator.name[6:], value_string))
37 value += 1
38 print('')
39
40
41 def read_cairo_header(cairo_git_dir, suffix):
42 filename = os.path.join(cairo_git_dir, 'src', 'cairo%s.h' % suffix)
43 source = open(filename, encoding='iso-8859-1').read()
44 source = re.sub(
45 '/\\*.*?\\*/'
46 '|CAIRO_(BEGIN|END)_DECLS'
47 '|cairo_public '
48 r'|^\s*#.*?[^\\]\n',
49 '',
50 source,
51 flags=re.DOTALL | re.MULTILINE)
52 source = re.sub('\n{3,}', '\n\n', source)
53 return source
54
55
56 def generate(cairo_git_dir):
57 # Remove comments, preprocessor instructions and macros.
58 source = read_cairo_header(cairo_git_dir, '')
59
60 source += 'const int CAIRO_PDF_OUTLINE_ROOT = 0;\n'
61 source += read_cairo_header(cairo_git_dir, '-pdf')
62
63 source += read_cairo_header(cairo_git_dir, '-ps')
64
65 source += read_cairo_header(cairo_git_dir, '-svg')
66
67 source += '''
68 typedef void* HDC;
69 typedef void* HFONT;
70 typedef void LOGFONTW;
71 '''
72 source += read_cairo_header(cairo_git_dir, '-win32')
73
74 source += '''
75 typedef void* CGContextRef;
76 typedef void* CGFontRef;
77 typedef void* ATSUFontID;
78 '''
79 source += read_cairo_header(cairo_git_dir, '-quartz')
80
81 ast = pycparser.CParser().parse(source)
82
83 print(textwrap.dedent('''\
84 # *** Do not edit this file ***
85 # Generated by utils/mkconstants.py
86 # flake8: noqa
87
88 TAG_DEST = b"cairo.dest"
89 TAG_LINK = b"Link"\n'''))
90 PrintEnumsVisitor().visit(ast)
91 print('_CAIRO_HEADERS = r"""%s"""' % source)
92
93 source = read_cairo_header(cairo_git_dir, '-xcb')
94 print('_CAIRO_XCB_HEADERS = r"""%s"""' % source)
95
96
97 if __name__ == '__main__':
98 if len(sys.argv) >= 2:
99 generate(sys.argv[1])
100 else:
101 print('Usage: %s path/to/cairo_source.git' % sys.argv[0])