python: Use the print function
[mesa.git] / src / mapi / mapi_abi.py
1
2 # Mesa 3-D graphics library
3 #
4 # Copyright (C) 2010 LunarG Inc.
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a
7 # copy of this software and associated documentation files (the "Software"),
8 # to deal in the Software without restriction, including without limitation
9 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 # and/or sell copies of the Software, and to permit persons to whom the
11 # Software is furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included
14 # in all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 # DEALINGS IN THE SOFTWARE.
23 #
24 # Authors:
25 # Chia-I Wu <olv@lunarg.com>
26
27 from __future__ import print_function
28
29 import sys
30 # make it possible to import glapi
31 import os
32 GLAPI = os.path.join(".", os.path.dirname(sys.argv[0]), "glapi/gen")
33 sys.path.append(GLAPI)
34
35 import re
36 from optparse import OptionParser
37 import gl_XML
38 import glX_XML
39
40
41 # number of dynamic entries
42 ABI_NUM_DYNAMIC_ENTRIES = 256
43
44 class ABIEntry(object):
45 """Represent an ABI entry."""
46
47 _match_c_param = re.compile(
48 '^(?P<type>[\w\s*]+?)(?P<name>\w+)(\[(?P<array>\d+)\])?$')
49
50 def __init__(self, cols, attrs, xml_data = None):
51 self._parse(cols)
52
53 self.slot = attrs['slot']
54 self.hidden = attrs['hidden']
55 self.alias = attrs['alias']
56 self.handcode = attrs['handcode']
57 self.xml_data = xml_data
58
59 def c_prototype(self):
60 return '%s %s(%s)' % (self.c_return(), self.name, self.c_params())
61
62 def c_return(self):
63 ret = self.ret
64 if not ret:
65 ret = 'void'
66
67 return ret
68
69 def c_params(self):
70 """Return the parameter list used in the entry prototype."""
71 c_params = []
72 for t, n, a in self.params:
73 sep = '' if t.endswith('*') else ' '
74 arr = '[%d]' % a if a else ''
75 c_params.append(t + sep + n + arr)
76 if not c_params:
77 c_params.append('void')
78
79 return ", ".join(c_params)
80
81 def c_args(self):
82 """Return the argument list used in the entry invocation."""
83 c_args = []
84 for t, n, a in self.params:
85 c_args.append(n)
86
87 return ", ".join(c_args)
88
89 def _parse(self, cols):
90 ret = cols.pop(0)
91 if ret == 'void':
92 ret = None
93
94 name = cols.pop(0)
95
96 params = []
97 if not cols:
98 raise Exception(cols)
99 elif len(cols) == 1 and cols[0] == 'void':
100 pass
101 else:
102 for val in cols:
103 params.append(self._parse_param(val))
104
105 self.ret = ret
106 self.name = name
107 self.params = params
108
109 def _parse_param(self, c_param):
110 m = self._match_c_param.match(c_param)
111 if not m:
112 raise Exception('unrecognized param ' + c_param)
113
114 c_type = m.group('type').strip()
115 c_name = m.group('name')
116 c_array = m.group('array')
117 c_array = int(c_array) if c_array else 0
118
119 return (c_type, c_name, c_array)
120
121 def __str__(self):
122 return self.c_prototype()
123
124 def __cmp__(self, other):
125 # compare slot, alias, and then name
126 res = cmp(self.slot, other.slot)
127 if not res:
128 if not self.alias:
129 res = -1
130 elif not other.alias:
131 res = 1
132
133 if not res:
134 res = cmp(self.name, other.name)
135
136 return res
137
138 def abi_parse_xml(xml):
139 """Parse a GLAPI XML file for ABI entries."""
140 api = gl_XML.parse_GL_API(xml, glX_XML.glx_item_factory())
141
142 entry_dict = {}
143 for func in api.functionIterateByOffset():
144 # make sure func.name appear first
145 entry_points = func.entry_points[:]
146 entry_points.remove(func.name)
147 entry_points.insert(0, func.name)
148
149 for name in entry_points:
150 attrs = {
151 'slot': func.offset,
152 'hidden': not func.is_static_entry_point(name),
153 'alias': None if name == func.name else func.name,
154 'handcode': bool(func.has_different_protocol(name)),
155 }
156
157 # post-process attrs
158 if attrs['alias']:
159 try:
160 alias = entry_dict[attrs['alias']]
161 except KeyError:
162 raise Exception('failed to alias %s' % attrs['alias'])
163 if alias.alias:
164 raise Exception('recursive alias %s' % ent.name)
165 attrs['alias'] = alias
166 if attrs['handcode']:
167 attrs['handcode'] = func.static_glx_name(name)
168 else:
169 attrs['handcode'] = None
170
171 if entry_dict.has_key(name):
172 raise Exception('%s is duplicated' % (name))
173
174 cols = []
175 cols.append(func.return_type)
176 cols.append(name)
177 params = func.get_parameter_string(name)
178 cols.extend([p.strip() for p in params.split(',')])
179
180 ent = ABIEntry(cols, attrs, func)
181 entry_dict[ent.name] = ent
182
183 entries = entry_dict.values()
184 entries.sort()
185
186 return entries
187
188 def abi_parse_line(line):
189 cols = [col.strip() for col in line.split(',')]
190
191 attrs = {
192 'slot': -1,
193 'hidden': False,
194 'alias': None,
195 'handcode': None,
196 }
197
198 # extract attributes from the first column
199 vals = cols[0].split(':')
200 while len(vals) > 1:
201 val = vals.pop(0)
202 if val.startswith('slot='):
203 attrs['slot'] = int(val[5:])
204 elif val == 'hidden':
205 attrs['hidden'] = True
206 elif val.startswith('alias='):
207 attrs['alias'] = val[6:]
208 elif val.startswith('handcode='):
209 attrs['handcode'] = val[9:]
210 elif not val:
211 pass
212 else:
213 raise Exception('unknown attribute %s' % val)
214 cols[0] = vals[0]
215
216 return (attrs, cols)
217
218 def abi_parse(filename):
219 """Parse a CSV file for ABI entries."""
220 fp = open(filename) if filename != '-' else sys.stdin
221 lines = [line.strip() for line in fp.readlines()
222 if not line.startswith('#') and line.strip()]
223
224 entry_dict = {}
225 next_slot = 0
226 for line in lines:
227 attrs, cols = abi_parse_line(line)
228
229 # post-process attributes
230 if attrs['alias']:
231 try:
232 alias = entry_dict[attrs['alias']]
233 except KeyError:
234 raise Exception('failed to alias %s' % attrs['alias'])
235 if alias.alias:
236 raise Exception('recursive alias %s' % ent.name)
237 slot = alias.slot
238 attrs['alias'] = alias
239 else:
240 slot = next_slot
241 next_slot += 1
242
243 if attrs['slot'] < 0:
244 attrs['slot'] = slot
245 elif attrs['slot'] != slot:
246 raise Exception('invalid slot in %s' % (line))
247
248 ent = ABIEntry(cols, attrs)
249 if entry_dict.has_key(ent.name):
250 raise Exception('%s is duplicated' % (ent.name))
251 entry_dict[ent.name] = ent
252
253 entries = entry_dict.values()
254 entries.sort()
255
256 return entries
257
258 def abi_sanity_check(entries):
259 if not entries:
260 return
261
262 all_names = []
263 last_slot = entries[-1].slot
264 i = 0
265 for slot in xrange(last_slot + 1):
266 if entries[i].slot != slot:
267 raise Exception('entries are not ordered by slots')
268 if entries[i].alias:
269 raise Exception('first entry of slot %d aliases %s'
270 % (slot, entries[i].alias.name))
271 handcode = None
272 while i < len(entries) and entries[i].slot == slot:
273 ent = entries[i]
274 if not handcode and ent.handcode:
275 handcode = ent.handcode
276 elif ent.handcode != handcode:
277 raise Exception('two aliases with handcode %s != %s',
278 ent.handcode, handcode)
279
280 if ent.name in all_names:
281 raise Exception('%s is duplicated' % (ent.name))
282 if ent.alias and ent.alias.name not in all_names:
283 raise Exception('failed to alias %s' % (ent.alias.name))
284 all_names.append(ent.name)
285 i += 1
286 if i < len(entries):
287 raise Exception('there are %d invalid entries' % (len(entries) - 1))
288
289 class ABIPrinter(object):
290 """MAPI Printer"""
291
292 def __init__(self, entries):
293 self.entries = entries
294
295 # sort entries by their names
296 self.entries_sorted_by_names = self.entries[:]
297 self.entries_sorted_by_names.sort(lambda x, y: cmp(x.name, y.name))
298
299 self.indent = ' ' * 3
300 self.noop_warn = 'noop_warn'
301 self.noop_generic = 'noop_generic'
302 self.current_get = 'entry_current_get'
303
304 self.api_defines = []
305 self.api_headers = ['"KHR/khrplatform.h"']
306 self.api_call = 'KHRONOS_APICALL'
307 self.api_entry = 'KHRONOS_APIENTRY'
308 self.api_attrs = 'KHRONOS_APIATTRIBUTES'
309
310 self.c_header = ''
311
312 self.lib_need_table_size = True
313 self.lib_need_noop_array = True
314 self.lib_need_stubs = True
315 self.lib_need_all_entries = True
316 self.lib_need_non_hidden_entries = False
317
318 def c_notice(self):
319 return '/* This file is automatically generated by mapi_abi.py. Do not modify. */'
320
321 def c_public_includes(self):
322 """Return includes of the client API headers."""
323 defines = ['#define ' + d for d in self.api_defines]
324 includes = ['#include ' + h for h in self.api_headers]
325 return "\n".join(defines + includes)
326
327 def need_entry_point(self, ent):
328 """Return True if an entry point is needed for the entry."""
329 # non-handcode hidden aliases may share the entry they alias
330 use_alias = (ent.hidden and ent.alias and not ent.handcode)
331 return not use_alias
332
333 def c_public_declarations(self, prefix):
334 """Return the declarations of public entry points."""
335 decls = []
336 for ent in self.entries:
337 if not self.need_entry_point(ent):
338 continue
339 export = self.api_call if not ent.hidden else ''
340 decls.append(self._c_decl(ent, prefix, True, export) + ';')
341
342 return "\n".join(decls)
343
344 def c_mapi_table(self):
345 """Return defines of the dispatch table size."""
346 num_static_entries = self.entries[-1].slot + 1
347 return ('#define MAPI_TABLE_NUM_STATIC %d\n' + \
348 '#define MAPI_TABLE_NUM_DYNAMIC %d') % (
349 num_static_entries, ABI_NUM_DYNAMIC_ENTRIES)
350
351 def _c_function(self, ent, prefix, mangle=False, stringify=False):
352 """Return the function name of an entry."""
353 formats = {
354 True: { True: '%s_STR(%s)', False: '%s(%s)' },
355 False: { True: '"%s%s"', False: '%s%s' },
356 }
357 fmt = formats[prefix.isupper()][stringify]
358 name = ent.name
359 if mangle and ent.hidden:
360 name = '_dispatch_stub_' + str(ent.slot)
361 return fmt % (prefix, name)
362
363 def _c_function_call(self, ent, prefix):
364 """Return the function name used for calling."""
365 if ent.handcode:
366 # _c_function does not handle this case
367 formats = { True: '%s(%s)', False: '%s%s' }
368 fmt = formats[prefix.isupper()]
369 name = fmt % (prefix, ent.handcode)
370 elif self.need_entry_point(ent):
371 name = self._c_function(ent, prefix, True)
372 else:
373 name = self._c_function(ent.alias, prefix, True)
374 return name
375
376 def _c_decl(self, ent, prefix, mangle=False, export=''):
377 """Return the C declaration for the entry."""
378 decl = '%s %s %s(%s)' % (ent.c_return(), self.api_entry,
379 self._c_function(ent, prefix, mangle), ent.c_params())
380 if export:
381 decl = export + ' ' + decl
382 if self.api_attrs:
383 decl += ' ' + self.api_attrs
384
385 return decl
386
387 def _c_cast(self, ent):
388 """Return the C cast for the entry."""
389 cast = '%s (%s *)(%s)' % (
390 ent.c_return(), self.api_entry, ent.c_params())
391
392 return cast
393
394 def c_public_dispatches(self, prefix, no_hidden):
395 """Return the public dispatch functions."""
396 dispatches = []
397 for ent in self.entries:
398 if ent.hidden and no_hidden:
399 continue
400
401 if not self.need_entry_point(ent):
402 continue
403
404 export = self.api_call if not ent.hidden else ''
405
406 proto = self._c_decl(ent, prefix, True, export)
407 cast = self._c_cast(ent)
408
409 ret = ''
410 if ent.ret:
411 ret = 'return '
412 stmt1 = self.indent
413 stmt1 += 'const struct _glapi_table *_tbl = %s();' % (
414 self.current_get)
415 stmt2 = self.indent
416 stmt2 += 'mapi_func _func = ((const mapi_func *) _tbl)[%d];' % (
417 ent.slot)
418 stmt3 = self.indent
419 stmt3 += '%s((%s) _func)(%s);' % (ret, cast, ent.c_args())
420
421 disp = '%s\n{\n%s\n%s\n%s\n}' % (proto, stmt1, stmt2, stmt3)
422
423 if ent.handcode:
424 disp = '#if 0\n' + disp + '\n#endif'
425
426 dispatches.append(disp)
427
428 return '\n\n'.join(dispatches)
429
430 def c_public_initializer(self, prefix):
431 """Return the initializer for public dispatch functions."""
432 names = []
433 for ent in self.entries:
434 if ent.alias:
435 continue
436
437 name = '%s(mapi_func) %s' % (self.indent,
438 self._c_function_call(ent, prefix))
439 names.append(name)
440
441 return ',\n'.join(names)
442
443 def c_stub_string_pool(self):
444 """Return the string pool for use by stubs."""
445 # sort entries by their names
446 sorted_entries = self.entries[:]
447 sorted_entries.sort(lambda x, y: cmp(x.name, y.name))
448
449 pool = []
450 offsets = {}
451 count = 0
452 for ent in sorted_entries:
453 offsets[ent] = count
454 pool.append('%s' % (ent.name))
455 count += len(ent.name) + 1
456
457 pool_str = self.indent + '"' + \
458 ('\\0"\n' + self.indent + '"').join(pool) + '";'
459 return (pool_str, offsets)
460
461 def c_stub_initializer(self, prefix, pool_offsets):
462 """Return the initializer for struct mapi_stub array."""
463 stubs = []
464 for ent in self.entries_sorted_by_names:
465 stubs.append('%s{ (void *) %d, %d, NULL }' % (
466 self.indent, pool_offsets[ent], ent.slot))
467
468 return ',\n'.join(stubs)
469
470 def c_noop_functions(self, prefix, warn_prefix):
471 """Return the noop functions."""
472 noops = []
473 for ent in self.entries:
474 if ent.alias:
475 continue
476
477 proto = self._c_decl(ent, prefix, False, 'static')
478
479 stmt1 = self.indent;
480 space = ''
481 for t, n, a in ent.params:
482 stmt1 += "%s(void) %s;" % (space, n)
483 space = ' '
484
485 if ent.params:
486 stmt1 += '\n';
487
488 stmt1 += self.indent + '%s(%s);' % (self.noop_warn,
489 self._c_function(ent, warn_prefix, False, True))
490
491 if ent.ret:
492 stmt2 = self.indent + 'return (%s) 0;' % (ent.ret)
493 noop = '%s\n{\n%s\n%s\n}' % (proto, stmt1, stmt2)
494 else:
495 noop = '%s\n{\n%s\n}' % (proto, stmt1)
496
497 noops.append(noop)
498
499 return '\n\n'.join(noops)
500
501 def c_noop_initializer(self, prefix, use_generic):
502 """Return an initializer for the noop dispatch table."""
503 entries = [self._c_function(ent, prefix)
504 for ent in self.entries if not ent.alias]
505 if use_generic:
506 entries = [self.noop_generic] * len(entries)
507
508 entries.extend([self.noop_generic] * ABI_NUM_DYNAMIC_ENTRIES)
509
510 pre = self.indent + '(mapi_func) '
511 return pre + (',\n' + pre).join(entries)
512
513 def c_asm_gcc(self, prefix, no_hidden):
514 asm = []
515
516 for ent in self.entries:
517 if ent.hidden and no_hidden:
518 continue
519
520 if not self.need_entry_point(ent):
521 continue
522
523 name = self._c_function(ent, prefix, True, True)
524
525 if ent.handcode:
526 asm.append('#if 0')
527
528 if ent.hidden:
529 asm.append('".hidden "%s"\\n"' % (name))
530
531 if ent.alias and not (ent.alias.hidden and no_hidden):
532 asm.append('".globl "%s"\\n"' % (name))
533 asm.append('".set "%s", "%s"\\n"' % (name,
534 self._c_function(ent.alias, prefix, True, True)))
535 else:
536 asm.append('STUB_ASM_ENTRY(%s)"\\n"' % (name))
537 asm.append('"\\t"STUB_ASM_CODE("%d")"\\n"' % (ent.slot))
538
539 if ent.handcode:
540 asm.append('#endif')
541 asm.append('')
542
543 return "\n".join(asm)
544
545 def output_for_lib(self):
546 print(self.c_notice())
547
548 if self.c_header:
549 print()
550 print(self.c_header)
551
552 print()
553 print('#ifdef MAPI_TMP_DEFINES')
554 print(self.c_public_includes())
555 print()
556 print(self.c_public_declarations(self.prefix_lib))
557 print('#undef MAPI_TMP_DEFINES')
558 print('#endif /* MAPI_TMP_DEFINES */')
559
560 if self.lib_need_table_size:
561 print()
562 print('#ifdef MAPI_TMP_TABLE')
563 print(self.c_mapi_table())
564 print('#undef MAPI_TMP_TABLE')
565 print('#endif /* MAPI_TMP_TABLE */')
566
567 if self.lib_need_noop_array:
568 print()
569 print('#ifdef MAPI_TMP_NOOP_ARRAY')
570 print('#ifdef DEBUG')
571 print()
572 print(self.c_noop_functions(self.prefix_noop, self.prefix_warn))
573 print()
574 print('const mapi_func table_%s_array[] = {' % (self.prefix_noop))
575 print(self.c_noop_initializer(self.prefix_noop, False))
576 print('};')
577 print()
578 print('#else /* DEBUG */')
579 print()
580 print('const mapi_func table_%s_array[] = {' % (self.prefix_noop))
581 print(self.c_noop_initializer(self.prefix_noop, True))
582 print('};')
583 print()
584 print('#endif /* DEBUG */')
585 print('#undef MAPI_TMP_NOOP_ARRAY')
586 print('#endif /* MAPI_TMP_NOOP_ARRAY */')
587
588 if self.lib_need_stubs:
589 pool, pool_offsets = self.c_stub_string_pool()
590 print()
591 print('#ifdef MAPI_TMP_PUBLIC_STUBS')
592 print('static const char public_string_pool[] =')
593 print(pool)
594 print()
595 print('static const struct mapi_stub public_stubs[] = {')
596 print(self.c_stub_initializer(self.prefix_lib, pool_offsets))
597 print('};')
598 print('#undef MAPI_TMP_PUBLIC_STUBS')
599 print('#endif /* MAPI_TMP_PUBLIC_STUBS */')
600
601 if self.lib_need_all_entries:
602 print()
603 print('#ifdef MAPI_TMP_PUBLIC_ENTRIES')
604 print(self.c_public_dispatches(self.prefix_lib, False))
605 print()
606 print('static const mapi_func public_entries[] = {')
607 print(self.c_public_initializer(self.prefix_lib))
608 print('};')
609 print('#undef MAPI_TMP_PUBLIC_ENTRIES')
610 print('#endif /* MAPI_TMP_PUBLIC_ENTRIES */')
611
612 print()
613 print('#ifdef MAPI_TMP_STUB_ASM_GCC')
614 print('__asm__(')
615 print(self.c_asm_gcc(self.prefix_lib, False))
616 print(');')
617 print('#undef MAPI_TMP_STUB_ASM_GCC')
618 print('#endif /* MAPI_TMP_STUB_ASM_GCC */')
619
620 if self.lib_need_non_hidden_entries:
621 all_hidden = True
622 for ent in self.entries:
623 if not ent.hidden:
624 all_hidden = False
625 break
626 if not all_hidden:
627 print()
628 print('#ifdef MAPI_TMP_PUBLIC_ENTRIES_NO_HIDDEN')
629 print(self.c_public_dispatches(self.prefix_lib, True))
630 print()
631 print('/* does not need public_entries */')
632 print('#undef MAPI_TMP_PUBLIC_ENTRIES_NO_HIDDEN')
633 print('#endif /* MAPI_TMP_PUBLIC_ENTRIES_NO_HIDDEN */')
634
635 print()
636 print('#ifdef MAPI_TMP_STUB_ASM_GCC_NO_HIDDEN')
637 print('__asm__(')
638 print(self.c_asm_gcc(self.prefix_lib, True))
639 print(');')
640 print('#undef MAPI_TMP_STUB_ASM_GCC_NO_HIDDEN')
641 print('#endif /* MAPI_TMP_STUB_ASM_GCC_NO_HIDDEN */')
642
643 class GLAPIPrinter(ABIPrinter):
644 """OpenGL API Printer"""
645
646 def __init__(self, entries):
647 for ent in entries:
648 self._override_for_api(ent)
649 super(GLAPIPrinter, self).__init__(entries)
650
651 self.api_defines = ['GL_GLEXT_PROTOTYPES']
652 self.api_headers = ['"GL/gl.h"', '"GL/glext.h"']
653 self.api_call = 'GLAPI'
654 self.api_entry = 'APIENTRY'
655 self.api_attrs = ''
656
657 self.lib_need_table_size = False
658 self.lib_need_noop_array = False
659 self.lib_need_stubs = False
660 self.lib_need_all_entries = False
661 self.lib_need_non_hidden_entries = True
662
663 self.prefix_lib = 'GLAPI_PREFIX'
664 self.prefix_noop = 'noop'
665 self.prefix_warn = self.prefix_lib
666
667 self.c_header = self._get_c_header()
668
669 def _override_for_api(self, ent):
670 """Override attributes of an entry if necessary for this
671 printer."""
672 # By default, no override is necessary.
673 pass
674
675 def _get_c_header(self):
676 header = """#ifndef _GLAPI_TMP_H_
677 #define _GLAPI_TMP_H_
678 #ifdef USE_MGL_NAMESPACE
679 #define GLAPI_PREFIX(func) mgl##func
680 #define GLAPI_PREFIX_STR(func) "mgl"#func
681 #else
682 #define GLAPI_PREFIX(func) gl##func
683 #define GLAPI_PREFIX_STR(func) "gl"#func
684 #endif /* USE_MGL_NAMESPACE */
685
686 typedef int GLclampx;
687 #endif /* _GLAPI_TMP_H_ */"""
688
689 return header
690
691 class ES1APIPrinter(GLAPIPrinter):
692 """OpenGL ES 1.x API Printer"""
693
694 def __init__(self, entries):
695 super(ES1APIPrinter, self).__init__(entries)
696 self.prefix_lib = 'gl'
697 self.prefix_warn = 'gl'
698
699 def _override_for_api(self, ent):
700 if ent.xml_data is None:
701 raise Exception('ES2 API printer requires XML input')
702 ent.hidden = (ent.name not in \
703 ent.xml_data.entry_points_for_api_version('es1')) \
704 or ent.hidden
705 ent.handcode = False
706
707 def _get_c_header(self):
708 header = """#ifndef _GLAPI_TMP_H_
709 #define _GLAPI_TMP_H_
710 typedef int GLclampx;
711 #endif /* _GLAPI_TMP_H_ */"""
712
713 return header
714
715 class ES2APIPrinter(GLAPIPrinter):
716 """OpenGL ES 2.x API Printer"""
717
718 def __init__(self, entries):
719 super(ES2APIPrinter, self).__init__(entries)
720 self.prefix_lib = 'gl'
721 self.prefix_warn = 'gl'
722
723 def _override_for_api(self, ent):
724 if ent.xml_data is None:
725 raise Exception('ES2 API printer requires XML input')
726 ent.hidden = (ent.name not in \
727 ent.xml_data.entry_points_for_api_version('es2')) \
728 or ent.hidden
729
730 # This is hella ugly. The same-named function in desktop OpenGL is
731 # hidden, but it needs to be exposed by libGLESv2 for OpenGL ES 3.0.
732 # There's no way to express in the XML that a function should be be
733 # hidden in one API but exposed in another.
734 if ent.name == 'GetInternalformativ':
735 ent.hidden = False
736
737 ent.handcode = False
738
739 def _get_c_header(self):
740 header = """#ifndef _GLAPI_TMP_H_
741 #define _GLAPI_TMP_H_
742 typedef int GLclampx;
743 #endif /* _GLAPI_TMP_H_ */"""
744
745 return header
746
747 class SharedGLAPIPrinter(GLAPIPrinter):
748 """Shared GLAPI API Printer"""
749
750 def __init__(self, entries):
751 super(SharedGLAPIPrinter, self).__init__(entries)
752
753 self.lib_need_table_size = True
754 self.lib_need_noop_array = True
755 self.lib_need_stubs = True
756 self.lib_need_all_entries = True
757 self.lib_need_non_hidden_entries = False
758
759 self.prefix_lib = 'shared'
760 self.prefix_warn = 'gl'
761
762 def _override_for_api(self, ent):
763 ent.hidden = True
764 ent.handcode = False
765
766 def _get_c_header(self):
767 header = """#ifndef _GLAPI_TMP_H_
768 #define _GLAPI_TMP_H_
769 typedef int GLclampx;
770 #endif /* _GLAPI_TMP_H_ */"""
771
772 return header
773
774 def parse_args():
775 printers = ['glapi', 'es1api', 'es2api', 'shared-glapi']
776
777 parser = OptionParser(usage='usage: %prog [options] <filename>')
778 parser.add_option('-p', '--printer', dest='printer',
779 help='printer to use: %s' % (", ".join(printers)))
780
781 options, args = parser.parse_args()
782 if not args or options.printer not in printers:
783 parser.print_help()
784 sys.exit(1)
785
786 return (args[0], options)
787
788 def main():
789 printers = {
790 'glapi': GLAPIPrinter,
791 'es1api': ES1APIPrinter,
792 'es2api': ES2APIPrinter,
793 'shared-glapi': SharedGLAPIPrinter,
794 }
795
796 filename, options = parse_args()
797
798 if filename.endswith('.xml'):
799 entries = abi_parse_xml(filename)
800 else:
801 entries = abi_parse(filename)
802 abi_sanity_check(entries)
803
804 printer = printers[options.printer](entries)
805 printer.output_for_lib()
806
807 if __name__ == '__main__':
808 main()