1 ########################################################################
2 # Copyright (c) 2000, BeOpen.com.
3 # Copyright (c) 1995-2000, Corporation for National Research Initiatives.
4 # Copyright (c) 1990-1995, Stichting Mathematisch Centrum.
7 # See the file "Misc/COPYRIGHT" for information on usage and
8 # redistribution of this file, and for a DISCLAIMER OF ALL WARRANTIES.
9 ########################################################################
11 # Python script to parse cstubs file for gl and generate C stubs.
12 # usage: python cgen.py <cstubs >glmodule.c
14 # NOTE: You must first make a python binary without the "GL" option
15 # before you can run this, when building Python for the first time.
16 # See comments in the Makefile.
18 # XXX BUG return arrays generate wrong code
19 # XXX need to change error returns into gotos to free mallocked arrays
26 # Function to print to stderr
29 savestdout
= sys
.stdout
31 sys
.stdout
= sys
.stderr
36 sys
.stdout
= savestdout
39 # The set of digits that form a number
44 # Function to extract a string of digits from the front of the string.
45 # Returns the leading string of digits and the remaining string.
46 # If no number is found, returns '' and the original string.
50 while s
and s
[0] in digits
:
56 # Function to check if a string is a number
59 if not s
: return False
61 if not c
in digits
: return False
65 # Allowed function return types
67 return_types
= ['void', 'short', 'long']
70 # Allowed function argument types
72 arg_types
= ['char', 'string', 'short', 'u_short', 'float', 'long', 'double']
75 # Need to classify arguments as follows
76 # simple input variable
77 # simple output variable
80 # input giving size of some array
82 # Array dimensions can be specified as follows
89 # The dimensions given as constants * something are really
90 # arrays of points where points are 2- 3- or 4-tuples
92 # We have to consider three lists:
93 # python input arguments
94 # C stub arguments (in & out)
95 # python output arguments (really return values)
97 # There is a mapping from python input arguments to the input arguments
98 # of the C stub, and a further mapping from C stub arguments to the
99 # python return values
102 # Exception raised by checkarg() and generate()
104 arg_error
= 'bad arg'
107 # Function to check one argument.
108 # Arguments: the type and the arg "name" (really mode plus subscript).
109 # Raises arg_error if something's wrong.
110 # Return type, mode, factor, rest of subscript; factor and rest may be empty.
112 def checkarg(type, arg
):
114 # Turn "char *x" into "string x".
116 if type == 'char' and arg
[0] == '*':
120 # Check that the type is supported.
122 if type not in arg_types
:
123 raise arg_error
, ('bad type', type)
125 type = 'unsigned ' + type[2:]
127 # Split it in the mode (first character) and the rest.
129 mode
, rest
= arg
[:1], arg
[1:]
131 # The mode must be 's' for send (= input) or 'r' for return argument.
133 if mode
not in ('r', 's'):
134 raise arg_error
, ('bad arg mode', mode
)
136 # Is it a simple argument: if so, we are done.
139 return type, mode
, '', ''
141 # Not a simple argument; must be an array.
142 # The 'rest' must be a subscript enclosed in [ and ].
143 # The subscript must be one of the following forms,
144 # otherwise we don't handle it (where N is a number):
151 if rest
[:1] <> '[' or rest
[-1:] <> ']':
152 raise arg_error
, ('subscript expected', rest
)
155 # Is there a leading number?
157 num
, sub
= getnum(sub
)
159 # There is a leading number
161 # The subscript is just a number
162 return type, mode
, num
, ''
164 # There is a factor prefix
167 raise arg_error
, ('\'*\' expected', sub
)
169 # size is retval -- must be a reply argument
171 raise arg_error
, ('non-r mode with [retval]', mode
)
172 elif not isnum(sub
) and (sub
[:3] <> 'arg' or not isnum(sub
[3:])):
173 raise arg_error
, ('bad subscript', sub
)
175 return type, mode
, num
, sub
178 # List of functions for which we have generated stubs
183 # Generate the stub for the given function, using the database of argument
184 # information build by successive calls to checkarg()
186 def generate(type, func
, database
):
188 # Check that we can handle this case:
189 # no variable size reply arrays yet
194 for a_type
, a_mode
, a_factor
, a_sub
in database
:
196 n_in_args
= n_in_args
+ 1
198 n_out_args
= n_out_args
+ 1
201 raise arg_error
, ('bad a_mode', a_mode
)
202 if (a_mode
== 'r' and a_sub
) or a_sub
== 'retval':
203 err('Function', func
, 'too complicated:',
204 a_type
, a_mode
, a_factor
, a_sub
)
205 print '/* XXX Too complicated to generate code for */'
208 functions
.append(func
)
213 print 'static PyObject *'
214 print 'gl_' + func
+ '(self, args)'
215 print '\tPyObject *self;'
216 print '\tPyObject *args;'
219 # Declare return value if any
222 print '\t' + type, 'retval;'
226 for i
in range(len(database
)):
227 a_type
, a_mode
, a_factor
, a_sub
= database
[i
]
230 if a_sub
and not isnum(a_sub
):
235 print 'arg' + repr(i
+1) + ket
,
236 if a_sub
and isnum(a_sub
):
237 print '[', a_sub
, ']',
239 print '[', a_factor
, ']',
242 # Find input arguments derived from array sizes
244 for i
in range(len(database
)):
245 a_type
, a_mode
, a_factor
, a_sub
= database
[i
]
246 if a_mode
== 's' and a_sub
[:3] == 'arg' and isnum(a_sub
[3:]):
247 # Sending a variable-length array
249 if 1 <= n
<= len(database
):
250 b_type
, b_mode
, b_factor
, b_sub
= database
[n
-1]
252 database
[n
-1] = b_type
, 'i', a_factor
, repr(i
)
253 n_in_args
= n_in_args
- 1
255 # Assign argument positions in the Python argument list
259 for i
in range(len(database
)):
260 a_type
, a_mode
, a_factor
, a_sub
= database
[i
]
267 # Get input arguments
269 for i
in range(len(database
)):
270 a_type
, a_mode
, a_factor
, a_sub
= database
[i
]
271 if a_type
[:9] == 'unsigned ':
278 # a_factor is divisor if present,
279 # a_sub indicates which arg (`database index`)
283 print '(!geti' + xtype
+ 'arraysize(args,',
284 print repr(n_in_args
) + ',',
285 print repr(in_pos
[j
]) + ',',
287 print '('+xtype
+' *)',
288 print '&arg' + repr(i
+1) + '))'
289 print '\t\treturn NULL;'
291 print '\targ' + repr(i
+1),
292 print '= arg' + repr(i
+1),
293 print '/', a_factor
+ ';'
295 if a_sub
and not isnum(a_sub
):
296 # Allocate memory for varsize array
297 print '\tif ((arg' + repr(i
+1), '=',
299 print '('+a_type
+'(*)['+a_factor
+'])',
300 print 'PyMem_NEW(' + a_type
, ',',
303 print a_sub
, ')) == NULL)'
304 print '\t\treturn PyErr_NoMemory();'
306 if a_factor
or a_sub
: # Get a fixed-size array array
307 print '(!geti' + xtype
+ 'array(args,',
308 print repr(n_in_args
) + ',',
309 print repr(in_pos
[i
]) + ',',
310 if a_factor
: print a_factor
,
311 if a_factor
and a_sub
: print '*',
312 if a_sub
: print a_sub
,
314 if (a_sub
and a_factor
) or xtype
<> a_type
:
315 print '('+xtype
+' *)',
316 print 'arg' + repr(i
+1) + '))'
317 else: # Get a simple variable
318 print '(!geti' + xtype
+ 'arg(args,',
319 print repr(n_in_args
) + ',',
320 print repr(in_pos
[i
]) + ',',
322 print '('+xtype
+' *)',
323 print '&arg' + repr(i
+1) + '))'
324 print '\t\treturn NULL;'
326 # Begin of function call
329 print '\tretval =', func
+ '(',
331 print '\t' + func
+ '(',
335 for i
in range(len(database
)):
337 a_type
, a_mode
, a_factor
, a_sub
= database
[i
]
338 if a_mode
== 'r' and not a_factor
:
340 print 'arg' + repr(i
+1),
342 # End of function call
346 # Free varsize arrays
348 for i
in range(len(database
)):
349 a_type
, a_mode
, a_factor
, a_sub
= database
[i
]
350 if a_mode
== 's' and a_sub
and not isnum(a_sub
):
351 print '\tPyMem_DEL(arg' + repr(i
+1) + ');'
357 # Multiple return values -- construct a tuple
360 n_out_args
= n_out_args
+ 1
362 for i
in range(len(database
)):
363 a_type
, a_mode
, a_factor
, a_sub
= database
[i
]
367 raise arg_error
, 'expected r arg not found'
369 print mkobject(a_type
, 'arg' + repr(i
+1)) + ';'
371 print '\t{ PyObject *v = PyTuple_New(',
372 print n_out_args
, ');'
373 print '\t if (v == NULL) return NULL;'
376 print '\t PyTuple_SetItem(v,',
377 print repr(i_out
) + ',',
378 print mkobject(type, 'retval') + ');'
380 for i
in range(len(database
)):
381 a_type
, a_mode
, a_factor
, a_sub
= database
[i
]
383 print '\t PyTuple_SetItem(v,',
384 print repr(i_out
) + ',',
385 s
= mkobject(a_type
, 'arg' + repr(i
+1))
392 # Simple function return
393 # Return None or return value
396 print '\tPy_INCREF(Py_None);'
397 print '\treturn Py_None;'
399 print '\treturn', mkobject(type, 'retval') + ';'
401 # Stub body closing brace
406 # Subroutine to return a function call to mknew<type>object(<arg>)
408 def mkobject(type, arg
):
409 if type[:9] == 'unsigned ':
411 return 'mknew' + type + 'object((' + type + ') ' + arg
+ ')'
412 return 'mknew' + type + 'object(' + arg
+ ')'
417 # usage: cgen [ -Dmach ... ] [ file ]
418 for arg
in sys
.argv
[1:]:
420 defined_archs
.append(arg
[2:])
422 # Open optional file argument
423 sys
.stdin
= open(arg
, 'r')
430 # Input is divided in two parts, separated by a line containing '%%'.
431 # <part1> -- literally copied to stdout
432 # <part2> -- stub definitions
434 # Variable indicating the current input part.
438 # Main loop over the input
447 words
= string
.split(line
)
451 # In part 1, copy everything literally
452 # except look for a line of just '%%'
458 # Look for names of manually written
459 # stubs: a single percent followed by the name
460 # of the function in Python.
461 # The stub name is derived by prefixing 'gl_'.
463 if words
and words
[0][0] == '%':
465 if (not func
) and words
[1:]:
468 functions
.append(func
)
473 continue # skip empty line
474 elif words
[0] == 'if':
477 if words
[1][0] == '!':
478 if words
[1][1:] in defined_archs
:
480 elif words
[1] not in defined_archs
:
483 if words
[0] == '#include':
485 elif words
[0][:1] == '#':
486 pass # ignore comment
487 elif words
[0] not in return_types
:
488 err('Line', lno
, ': bad return type :', words
[0])
490 err('Line', lno
, ': no funcname :', line
)
492 if len(words
) % 2 <> 0:
493 err('Line', lno
, ': odd argument list :', words
[2:])
497 for i
in range(2, len(words
), 2):
498 x
= checkarg(words
[i
], words
[i
+1])
502 for w
in words
: print w
,
504 generate(words
[0], words
[1], database
)
505 except arg_error
, msg
:
506 err('Line', lno
, ':', msg
)
510 print 'static struct PyMethodDef gl_methods[] = {'
511 for func
in functions
:
512 print '\t{"' + func
+ '", gl_' + func
+ '},'
513 print '\t{NULL, NULL} /* Sentinel */'
519 print '\t(void) Py_InitModule("gl", gl_methods);'