3 # Mesa 3-D graphics library
6 # Copyright (C) 2010 LunarG Inc.
8 # Permission is hereby granted, free of charge, to any person obtaining a
9 # copy of this software and associated documentation files (the "Software"),
10 # to deal in the Software without restriction, including without limitation
11 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 # and/or sell copies of the Software, and to permit persons to whom the
13 # Software is furnished to do so, subject to the following conditions:
15 # The above copyright notice and this permission notice shall be included
16 # in all copies or substantial portions of the Software.
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 # DEALINGS IN THE SOFTWARE.
27 # Chia-I Wu <olv@lunarg.com>
31 from optparse
import OptionParser
33 # number of dynamic entries
34 ABI_NUM_DYNAMIC_ENTRIES
= 256
36 class ABIEntry(object):
37 """Represent an ABI entry."""
39 _match_c_param
= re
.compile(
40 '^(?P<type>[\w\s*]+?)(?P<name>\w+)(\[(?P<array>\d+)\])?$')
42 def __init__(self
, cols
, attrs
):
45 self
.slot
= attrs
['slot']
46 self
.hidden
= attrs
['hidden']
47 self
.alias
= attrs
['alias']
48 self
.handcode
= attrs
['handcode']
50 def c_prototype(self
):
51 return '%s %s(%s)' % (self
.c_return(), self
.name
, self
.c_params())
61 """Return the parameter list used in the entry prototype."""
63 for t
, n
, a
in self
.params
:
64 sep
= '' if t
.endswith('*') else ' '
65 arr
= '[%d]' % a
if a
else ''
66 c_params
.append(t
+ sep
+ n
+ arr
)
68 c_params
.append('void')
70 return ", ".join(c_params
)
73 """Return the argument list used in the entry invocation."""
75 for t
, n
, a
in self
.params
:
78 return ", ".join(c_args
)
80 def _parse(self
, cols
):
90 elif len(cols
) == 1 and cols
[0] == 'void':
94 params
.append(self
._parse
_param
(val
))
100 def _parse_param(self
, c_param
):
101 m
= self
._match
_c
_param
.match(c_param
)
103 raise Exception('unrecognized param ' + c_param
)
105 c_type
= m
.group('type').strip()
106 c_name
= m
.group('name')
107 c_array
= m
.group('array')
108 c_array
= int(c_array
) if c_array
else 0
110 return (c_type
, c_name
, c_array
)
113 return self
.c_prototype()
115 def __cmp__(self
, other
):
116 # compare slot, alias, and then name
117 res
= cmp(self
.slot
, other
.slot
)
121 elif not other
.alias
:
125 res
= cmp(self
.name
, other
.name
)
129 def abi_parse_line(line
):
130 cols
= [col
.strip() for col
in line
.split(',')]
139 # extract attributes from the first column
140 vals
= cols
[0].split(':')
143 if val
.startswith('slot='):
144 attrs
['slot'] = int(val
[5:])
145 elif val
== 'hidden':
146 attrs
['hidden'] = True
147 elif val
.startswith('alias='):
148 attrs
['alias'] = val
[6:]
149 elif val
.startswith('handcode='):
150 attrs
['handcode'] = val
[9:]
154 raise Exception('unknown attribute %s' % val
)
159 def abi_parse(filename
):
160 """Parse a CSV file for ABI entries."""
161 fp
= open(filename
) if filename
!= '-' else sys
.stdin
162 lines
= [line
.strip() for line
in fp
.readlines()
163 if not line
.startswith('#') and line
.strip()]
168 attrs
, cols
= abi_parse_line(line
)
170 # post-process attributes
173 alias
= entry_dict
[attrs
['alias']]
175 raise Exception('failed to alias %s' % attrs
['alias'])
177 raise Exception('recursive alias %s' % ent
.name
)
179 attrs
['alias'] = alias
184 if attrs
['slot'] < 0:
186 elif attrs
['slot'] != slot
:
187 raise Exception('invalid slot in %s' % (line
))
189 ent
= ABIEntry(cols
, attrs
)
190 if entry_dict
.has_key(ent
.name
):
191 raise Exception('%s is duplicated' % (ent
.name
))
192 entry_dict
[ent
.name
] = ent
194 entries
= entry_dict
.values()
199 for slot
in xrange(next_slot
):
200 if entries
[i
].slot
!= slot
:
201 raise Exception('entries are not ordered by slots')
203 raise Exception('first entry of slot %d aliases %s'
204 % (slot
, entries
[i
].alias
.name
))
206 while i
< len(entries
) and entries
[i
].slot
== slot
:
208 if not handcode
and ent
.handcode
:
209 handcode
= ent
.handcode
210 elif ent
.handcode
!= handcode
:
211 raise Exception('two aliases with handcode %s != %s',
212 ent
.handcode
, handcode
)
215 raise Exception('there are %d invalid entries' % (len(entries
) - 1))
219 class ABIPrinter(object):
222 def __init__(self
, entries
):
223 self
.entries
= entries
225 # sort entries by their names
226 self
.entries_sorted_by_names
= self
.entries
[:]
227 self
.entries_sorted_by_names
.sort(lambda x
, y
: cmp(x
.name
, y
.name
))
229 self
.indent
= ' ' * 3
230 self
.noop_warn
= 'noop_warn'
231 self
.noop_generic
= 'noop_generic'
233 self
.api_defines
= []
234 self
.api_headers
= ['"KHR/khrplatform.h"']
235 self
.api_call
= 'KHRONOS_APICALL'
236 self
.api_entry
= 'KHRONOS_APIENTRY'
237 self
.api_attrs
= 'KHRONOS_APIATTRIBUTES'
239 self
.lib_need_table_size
= True
240 self
.lib_need_noop_array
= True
241 self
.lib_need_stubs
= True
242 self
.lib_need_entries
= True
245 return '/* This file is automatically generated by mapi_abi.py. Do not modify. */'
247 def c_public_includes(self
):
248 """Return includes of the client API headers."""
249 defines
= ['#define ' + d
for d
in self
.api_defines
]
250 includes
= ['#include ' + h
for h
in self
.api_headers
]
251 return "\n".join(defines
+ includes
)
253 def need_entry_point(self
, ent
):
254 """Return True if an entry point is needed for the entry."""
255 # non-handcode hidden aliases may share the entry they alias
256 use_alias
= (ent
.hidden
and ent
.alias
and not ent
.handcode
)
259 def c_public_declarations(self
, prefix
):
260 """Return the declarations of public entry points."""
262 for ent
in self
.entries
:
263 if not self
.need_entry_point(ent
):
265 export
= self
.api_call
if not ent
.hidden
else ''
266 decls
.append(self
._c
_decl
(ent
, prefix
, True, export
) + ';')
268 return "\n".join(decls
)
270 def c_mapi_table(self
):
271 """Return defines of the dispatch table size."""
272 num_static_entries
= 0
273 for ent
in self
.entries
:
275 num_static_entries
+= 1
277 return ('#define MAPI_TABLE_NUM_STATIC %d\n' + \
278 '#define MAPI_TABLE_NUM_DYNAMIC %d') % (
279 num_static_entries
, ABI_NUM_DYNAMIC_ENTRIES
)
281 def c_mapi_table_initializer(self
, prefix
):
282 """Return the array initializer for mapi_table_fill."""
283 entries
= [self
._c
_function
(ent
, prefix
)
284 for ent
in self
.entries
if not ent
.alias
]
285 pre
= self
.indent
+ '(mapi_proc) '
286 return pre
+ (',\n' + pre
).join(entries
)
288 def c_mapi_table_spec(self
):
289 """Return the spec for mapi_init."""
292 for ent
in self
.entries
:
297 line
+= '%s\\0' % ent
.name
301 return self
.indent
+ self
.indent
.join(specv1
)
303 def _c_function(self
, ent
, prefix
, mangle
=False, stringify
=False):
304 """Return the function name of an entry."""
305 formats
= { True: '"%s%s"', False: '%s%s' }
306 fmt
= formats
[stringify
]
308 if mangle
and ent
.hidden
:
309 name
= '_dispatch_stub_' + str(ent
.slot
)
310 return fmt
% (prefix
, name
)
312 def _c_function_call(self
, ent
, prefix
):
313 """Return the function name used for calling."""
315 # _c_function does not handle this case
317 name
= fmt
% (prefix
, ent
.handcode
)
318 elif self
.need_entry_point(ent
):
319 name
= self
._c
_function
(ent
, prefix
, True)
321 name
= self
._c
_function
(ent
.alias
, prefix
, True)
324 def _c_decl(self
, ent
, prefix
, mangle
=False, export
=''):
325 """Return the C declaration for the entry."""
326 decl
= '%s %s %s(%s)' % (ent
.c_return(), self
.api_entry
,
327 self
._c
_function
(ent
, prefix
, mangle
), ent
.c_params())
329 decl
= export
+ ' ' + decl
331 decl
+= ' ' + self
.api_attrs
335 def _c_cast(self
, ent
):
336 """Return the C cast for the entry."""
337 cast
= '%s (%s *)(%s)' % (
338 ent
.c_return(), self
.api_entry
, ent
.c_params())
342 def c_private_declarations(self
, prefix
):
343 """Return the declarations of private functions."""
344 decls
= [self
._c
_decl
(ent
, prefix
) + ';'
345 for ent
in self
.entries
if not ent
.alias
]
347 return "\n".join(decls
)
349 def c_public_dispatches(self
, prefix
):
350 """Return the public dispatch functions."""
352 for ent
in self
.entries
:
353 if not self
.need_entry_point(ent
):
356 export
= self
.api_call
if not ent
.hidden
else ''
358 proto
= self
._c
_decl
(ent
, prefix
, True, export
)
359 cast
= self
._c
_cast
(ent
)
365 stmt1
+= 'const struct mapi_table *tbl = u_current_get();'
367 stmt2
+= 'mapi_func func = ((const mapi_func *) tbl)[%d];' % (
370 stmt3
+= '%s((%s) func)(%s);' % (ret
, cast
, ent
.c_args())
372 disp
= '%s\n{\n%s\n%s\n%s\n}' % (proto
, stmt1
, stmt2
, stmt3
)
375 disp
= '#if 0\n' + disp
+ '\n#endif'
377 dispatches
.append(disp
)
379 return '\n\n'.join(dispatches
)
381 def c_public_initializer(self
, prefix
):
382 """Return the initializer for public dispatch functions."""
384 for ent
in self
.entries
:
388 name
= '%s(mapi_func) %s' % (self
.indent
,
389 self
._c
_function
_call
(ent
, prefix
))
392 return ',\n'.join(names
)
394 def c_stub_string_pool(self
):
395 """Return the string pool for use by stubs."""
396 # sort entries by their names
397 sorted_entries
= self
.entries
[:]
398 sorted_entries
.sort(lambda x
, y
: cmp(x
.name
, y
.name
))
403 for ent
in sorted_entries
:
405 pool
.append('%s' % (ent
.name
))
406 count
+= len(ent
.name
) + 1
408 pool_str
= self
.indent
+ '"' + \
409 ('\\0"\n' + self
.indent
+ '"').join(pool
) + '";'
410 return (pool_str
, offsets
)
412 def c_stub_initializer(self
, prefix
, pool_offsets
):
413 """Return the initializer for struct mapi_stub array."""
415 for ent
in self
.entries_sorted_by_names
:
416 stubs
.append('%s{ (void *) %d, %d, NULL }' % (
417 self
.indent
, pool_offsets
[ent
], ent
.slot
))
419 return ',\n'.join(stubs
)
421 def c_noop_functions(self
, prefix
, warn_prefix
):
422 """Return the noop functions."""
424 for ent
in self
.entries
:
428 proto
= self
._c
_decl
(ent
, prefix
, False, 'static')
430 stmt1
= self
.indent
+ '%s(%s);' % (self
.noop_warn
,
431 self
._c
_function
(ent
, warn_prefix
, False, True))
434 stmt2
= self
.indent
+ 'return (%s) 0;' % (ent
.ret
)
435 noop
= '%s\n{\n%s\n%s\n}' % (proto
, stmt1
, stmt2
)
437 noop
= '%s\n{\n%s\n}' % (proto
, stmt1
)
441 return '\n\n'.join(noops
)
443 def c_noop_initializer(self
, prefix
, use_generic
):
444 """Return an initializer for the noop dispatch table."""
445 entries
= [self
._c
_function
(ent
, prefix
)
446 for ent
in self
.entries
if not ent
.alias
]
448 entries
= [self
.noop_generic
] * len(entries
)
450 entries
.extend([self
.noop_generic
] * ABI_NUM_DYNAMIC_ENTRIES
)
452 pre
= self
.indent
+ '(mapi_func) '
453 return pre
+ (',\n' + pre
).join(entries
)
455 def c_asm_gcc(self
, prefix
):
458 asm
.append('__asm__(')
459 for ent
in self
.entries
:
460 if not self
.need_entry_point(ent
):
463 name
= self
._c
_function
(ent
, prefix
, True, True)
469 asm
.append('".hidden "%s"\\n"' % (name
))
472 asm
.append('".globl "%s"\\n"' % (name
))
473 asm
.append('".set "%s", "%s"\\n"' % (name
,
474 self
._c
_function
(ent
.alias
, prefix
, True, True)))
476 asm
.append('STUB_ASM_ENTRY(%s)"\\n"' % (name
))
477 asm
.append('"\\t"STUB_ASM_CODE("%d")"\\n"' % (ent
.slot
))
484 return "\n".join(asm
)
486 def output_for_lib(self
):
487 print self
.c_notice()
489 print '#ifdef MAPI_TMP_DEFINES'
490 print self
.c_public_includes()
492 print self
.c_public_declarations(self
.prefix_lib
)
493 print '#undef MAPI_TMP_DEFINES'
494 print '#endif /* MAPI_TMP_DEFINES */'
496 if self
.lib_need_table_size
:
498 print '#ifdef MAPI_TMP_TABLE'
499 print self
.c_mapi_table()
500 print '#undef MAPI_TMP_TABLE'
501 print '#endif /* MAPI_TMP_TABLE */'
503 if self
.lib_need_noop_array
:
505 print '#ifdef MAPI_TMP_NOOP_ARRAY'
508 print self
.c_noop_functions(self
.prefix_noop
, self
.prefix_lib
)
510 print 'const mapi_func table_%s_array[] = {' % (self
.prefix_noop
)
511 print self
.c_noop_initializer(self
.prefix_noop
, False)
514 print '#else /* DEBUG */'
516 print 'const mapi_func table_%s_array[] = {' % (self
.prefix_noop
)
517 print self
.c_noop_initializer(self
.prefix_noop
, True)
520 print '#endif /* DEBUG */'
521 print '#undef MAPI_TMP_NOOP_ARRAY'
522 print '#endif /* MAPI_TMP_NOOP_ARRAY */'
524 if self
.lib_need_stubs
:
525 pool
, pool_offsets
= self
.c_stub_string_pool()
527 print '#ifdef MAPI_TMP_PUBLIC_STUBS'
528 print 'static const char public_string_pool[] ='
531 print 'static const struct mapi_stub public_stubs[] = {'
532 print self
.c_stub_initializer(self
.prefix_lib
, pool_offsets
)
534 print '#undef MAPI_TMP_PUBLIC_STUBS'
535 print '#endif /* MAPI_TMP_PUBLIC_STUBS */'
537 if self
.lib_need_entries
:
539 print '#ifdef MAPI_TMP_PUBLIC_ENTRIES'
540 print self
.c_public_dispatches(self
.prefix_lib
)
542 print 'static const mapi_func public_entries[] = {'
543 print self
.c_public_initializer(self
.prefix_lib
)
545 print '#undef MAPI_TMP_PUBLIC_ENTRIES'
546 print '#endif /* MAPI_TMP_PUBLIC_ENTRIES */'
549 print '#ifdef MAPI_TMP_STUB_ASM_GCC'
550 print self
.c_asm_gcc(self
.prefix_lib
)
551 print '#undef MAPI_TMP_STUB_ASM_GCC'
552 print '#endif /* MAPI_TMP_STUB_ASM_GCC */'
554 def output_for_app(self
):
555 print self
.c_notice()
557 print self
.c_private_declarations(self
.prefix_app
)
559 print '#ifdef API_TMP_DEFINE_SPEC'
561 print 'static const char %s_spec[] =' % (self
.prefix_app
)
562 print self
.c_mapi_table_spec()
564 print 'static const mapi_proc %s_procs[] = {' % (self
.prefix_app
)
565 print self
.c_mapi_table_initializer(self
.prefix_app
)
568 print '#endif /* API_TMP_DEFINE_SPEC */'
570 class GLAPIPrinter(ABIPrinter
):
571 """OpenGL API Printer"""
573 def __init__(self
, entries
):
574 super(GLAPIPrinter
, self
).__init
__(entries
)
576 self
.api_defines
= ['GL_GLEXT_PROTOTYPES']
577 self
.api_headers
= ['"GL/gl.h"', '"GL/glext.h"']
578 self
.api_call
= 'GLAPI'
579 self
.api_entry
= 'APIENTRY'
582 self
.prefix_lib
= 'gl'
583 self
.prefix_app
= '_mesa_'
584 self
.prefix_noop
= 'noop'
586 def output_for_app(self
):
590 class ES1APIPrinter(GLAPIPrinter
):
591 """OpenGL ES 1.x API Printer"""
593 def __init__(self
, entries
):
594 super(ES1APIPrinter
, self
).__init
__(entries
)
596 self
.api_headers
= ['"GLES/gl.h"', '"GLES/glext.h"']
597 self
.api_call
= 'GL_API'
598 self
.api_entry
= 'GL_APIENTRY'
600 class ES2APIPrinter(GLAPIPrinter
):
601 """OpenGL ES 2.x API Printer"""
603 def __init__(self
, entries
):
604 super(ES2APIPrinter
, self
).__init
__(entries
)
606 self
.api_headers
= ['"GLES2/gl2.h"', '"GLES2/gl2ext.h"']
607 self
.api_call
= 'GL_APICALL'
608 self
.api_entry
= 'GL_APIENTRY'
610 class VGAPIPrinter(ABIPrinter
):
611 """OpenVG API Printer"""
613 def __init__(self
, entries
):
614 super(VGAPIPrinter
, self
).__init
__(entries
)
616 self
.api_defines
= ['VG_VGEXT_PROTOTYPES']
617 self
.api_headers
= ['"VG/openvg.h"', '"VG/vgext.h"']
618 self
.api_call
= 'VG_API_CALL'
619 self
.api_entry
= 'VG_API_ENTRY'
620 self
.api_attrs
= 'VG_API_EXIT'
622 self
.prefix_lib
= 'vg'
623 self
.prefix_app
= 'vega'
624 self
.prefix_noop
= 'noop'
627 printers
= ['glapi', 'es1api', 'es2api', 'vgapi']
628 modes
= ['lib', 'app']
630 parser
= OptionParser(usage
='usage: %prog [options] <filename>')
631 parser
.add_option('-p', '--printer', dest
='printer',
632 help='printer to use: %s' % (", ".join(printers
)))
633 parser
.add_option('-m', '--mode', dest
='mode',
634 help='target user: %s' % (", ".join(modes
)))
636 options
, args
= parser
.parse_args()
637 if not args
or options
.printer
not in printers
or \
638 options
.mode
not in modes
:
642 return (args
[0], options
)
646 'vgapi': VGAPIPrinter
,
647 'glapi': GLAPIPrinter
,
648 'es1api': ES1APIPrinter
,
649 'es2api': ES2APIPrinter
652 filename
, options
= parse_args()
654 entries
= abi_parse(filename
)
655 printer
= printers
[options
.printer
](entries
)
656 if options
.mode
== 'lib':
657 printer
.output_for_lib()
659 printer
.output_for_app()
661 if __name__
== '__main__':