cgen.py 13.3 KB
Newer Older
1
########################################################################
2 3 4
# Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
# The Netherlands.
#
5
#                         All Rights Reserved
6 7 8
#
# Permission to use, copy, modify, and distribute this software and its
# documentation for any purpose and without fee is hereby granted,
9
# provided that the above copyright notice appear in all copies and that
10
# both that copyright notice and this permission notice appear in
11
# supporting documentation, and that the names of Stichting Mathematisch
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# Centrum or CWI or Corporation for National Research Initiatives or
# CNRI not be used in advertising or publicity pertaining to
# distribution of the software without specific, written prior
# permission.
# 
# While CWI is the initial source for this software, a modified version
# is made available by the Corporation for National Research Initiatives
# (CNRI) at the Internet address ftp://ftp.python.org.
# 
# STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
# REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
# CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
# DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
# PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
# TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
29 30
########################################################################

Guido van Rossum's avatar
Guido van Rossum committed
31
# Python script to parse cstubs file for gl and generate C stubs.
32
# usage: python cgen.py <cstubs >glmodule.c
Guido van Rossum's avatar
Guido van Rossum committed
33
#
34 35 36 37
# NOTE: You  must first make a python binary without the "GL" option
#	before you can run this, when building Python for the first time.
#	See comments in the Makefile.
#
Guido van Rossum's avatar
Guido van Rossum committed
38 39 40 41 42 43 44 45 46 47
# XXX BUG return arrays generate wrong code
# XXX need to change error returns into gotos to free mallocked arrays


import string
import sys


# Function to print to stderr
#
48
def err(*args):
Guido van Rossum's avatar
Guido van Rossum committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
	savestdout = sys.stdout
	try:
		sys.stdout = sys.stderr
		for i in args:
			print i,
		print
	finally:
		sys.stdout = savestdout


# The set of digits that form a number
#
digits = '0123456789'


# Function to extract a string of digits from the front of the string.
# Returns the leading string of digits and the remaining string.
# If no number is found, returns '' and the original string.
#
def getnum(s):
	n = ''
Guido van Rossum's avatar
Guido van Rossum committed
70 71
	while s and s[0] in digits:
		n = n + s[0]
Guido van Rossum's avatar
Guido van Rossum committed
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
		s = s[1:]
	return n, s


# Function to check if a string is a number
#
def isnum(s):
	if not s: return 0
	for c in s:
		if not c in digits: return 0
	return 1


# Allowed function return types
#
return_types = ['void', 'short', 'long']


# Allowed function argument types
#
92
arg_types = ['char', 'string', 'short', 'u_short', 'float', 'long', 'double']
Guido van Rossum's avatar
Guido van Rossum committed
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135


# Need to classify arguments as follows
#	simple input variable
#	simple output variable
#	input array
#	output array
#	input giving size of some array
#
# Array dimensions can be specified as follows
#	constant
#	argN
#	constant * argN
#	retval
#	constant * retval
#
# The dimensions given as constants * something are really
# arrays of points where points are 2- 3- or 4-tuples
#
# We have to consider three lists:
#	python input arguments
#	C stub arguments (in & out)
#	python output arguments (really return values)
#
# There is a mapping from python input arguments to the input arguments
# of the C stub, and a further mapping from C stub arguments to the
# python return values


# Exception raised by checkarg() and generate()
#
arg_error = 'bad arg'


# Function to check one argument.
# Arguments: the type and the arg "name" (really mode plus subscript).
# Raises arg_error if something's wrong.
# Return type, mode, factor, rest of subscript; factor and rest may be empty.
#
def checkarg(type, arg):
	#
	# Turn "char *x" into "string x".
	#
136
	if type == 'char' and arg[0] == '*':
Guido van Rossum's avatar
Guido van Rossum committed
137 138 139 140 141 142 143
		type = 'string'
		arg = arg[1:]
	#
	# Check that the type is supported.
	#
	if type not in arg_types:
		raise arg_error, ('bad type', type)
144 145
	if type[:2] == 'u_':
		type = 'unsigned ' + type[2:]
Guido van Rossum's avatar
Guido van Rossum committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
	#
	# Split it in the mode (first character) and the rest.
	#
	mode, rest = arg[:1], arg[1:]
	#
	# The mode must be 's' for send (= input) or 'r' for return argument.
	#
	if mode not in ('r', 's'):
		raise arg_error, ('bad arg mode', mode)
	#
	# Is it a simple argument: if so, we are done.
	#
	if not rest:
		return type, mode, '', ''
	#	
	# Not a simple argument; must be an array.
	# The 'rest' must be a subscript enclosed in [ and ].
	# The subscript must be one of the following forms,
	# otherwise we don't handle it (where N is a number):
	#	N
	#	argN
	#	retval
	#	N*argN
	#	N*retval
	#
	if rest[:1] <> '[' or rest[-1:] <> ']':
		raise arg_error, ('subscript expected', rest)
	sub = rest[1:-1]
	#
	# Is there a leading number?
	#
	num, sub = getnum(sub)
	if num:
		# There is a leading number
		if not sub:
			# The subscript is just a number
			return type, mode, num, ''
183
		if sub[:1] == '*':
Guido van Rossum's avatar
Guido van Rossum committed
184 185 186 187
			# There is a factor prefix
			sub = sub[1:]
		else:
			raise arg_error, ('\'*\' expected', sub)
188
	if sub == 'retval':
Guido van Rossum's avatar
Guido van Rossum committed
189 190 191
		# size is retval -- must be a reply argument
		if mode <> 'r':
			raise arg_error, ('non-r mode with [retval]', mode)
192
	elif not isnum(sub) and (sub[:3] <> 'arg' or not isnum(sub[3:])):
Guido van Rossum's avatar
Guido van Rossum committed
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
		raise arg_error, ('bad subscript', sub)
	#
	return type, mode, num, sub


# List of functions for which we have generated stubs
#
functions = []


# Generate the stub for the given function, using the database of argument
# information build by successive calls to checkarg()
#
def generate(type, func, database):
	#
	# Check that we can handle this case:
	# no variable size reply arrays yet
	#
	n_in_args = 0
	n_out_args = 0
	#
	for a_type, a_mode, a_factor, a_sub in database:
215
		if a_mode == 's':
Guido van Rossum's avatar
Guido van Rossum committed
216
			n_in_args = n_in_args + 1
217
		elif a_mode == 'r':
Guido van Rossum's avatar
Guido van Rossum committed
218 219 220 221
			n_out_args = n_out_args + 1
		else:
			# Can't happen
			raise arg_error, ('bad a_mode', a_mode)
222
		if (a_mode == 'r' and a_sub) or a_sub == 'retval':
223 224
			err('Function', func, 'too complicated:',
			    a_type, a_mode, a_factor, a_sub)
Guido van Rossum's avatar
Guido van Rossum committed
225 226 227 228 229 230 231 232
			print '/* XXX Too complicated to generate code for */'
			return
	#
	functions.append(func)
	#
	# Stub header
	#
	print
Guido van Rossum's avatar
Guido van Rossum committed
233
	print 'static PyObject *'
Guido van Rossum's avatar
Guido van Rossum committed
234
	print 'gl_' + func + '(self, args)'
Guido van Rossum's avatar
Guido van Rossum committed
235 236
	print '\tPyObject *self;'
	print '\tPyObject *args;'
Guido van Rossum's avatar
Guido van Rossum committed
237 238 239 240 241 242 243 244 245 246 247 248
	print '{'
	#
	# Declare return value if any
	#
	if type <> 'void':
		print '\t' + type, 'retval;'
	#
	# Declare arguments
	#
	for i in range(len(database)):
		a_type, a_mode, a_factor, a_sub = database[i]
		print '\t' + a_type,
249 250 251 252 253 254 255 256 257 258
		brac = ket = ''
		if a_sub and not isnum(a_sub):
			if a_factor:
				brac = '('
				ket = ')'
			print brac + '*',
		print 'arg' + `i+1` + ket,
		if a_sub and isnum(a_sub):
			print '[', a_sub, ']',
		if a_factor:
Guido van Rossum's avatar
Guido van Rossum committed
259 260 261 262 263 264 265
			print '[', a_factor, ']',
		print ';'
	#
	# Find input arguments derived from array sizes
	#
	for i in range(len(database)):
		a_type, a_mode, a_factor, a_sub = database[i]
266
		if a_mode == 's' and a_sub[:3] == 'arg' and isnum(a_sub[3:]):
Guido van Rossum's avatar
Guido van Rossum committed
267 268 269 270
			# Sending a variable-length array
			n = eval(a_sub[3:])
			if 1 <= n <= len(database):
			    b_type, b_mode, b_factor, b_sub = database[n-1]
271
			    if b_mode == 's':
Guido van Rossum's avatar
Guido van Rossum committed
272 273 274 275 276 277 278 279 280
			        database[n-1] = b_type, 'i', a_factor, `i`
			        n_in_args = n_in_args - 1
	#
	# Assign argument positions in the Python argument list
	#
	in_pos = []
	i_in = 0
	for i in range(len(database)):
		a_type, a_mode, a_factor, a_sub = database[i]
281
		if a_mode == 's':
Guido van Rossum's avatar
Guido van Rossum committed
282 283 284 285 286 287 288 289 290
			in_pos.append(i_in)
			i_in = i_in + 1
		else:
			in_pos.append(-1)
	#
	# Get input arguments
	#
	for i in range(len(database)):
		a_type, a_mode, a_factor, a_sub = database[i]
291 292 293 294
		if a_type[:9] == 'unsigned ':
			xtype = a_type[9:]
		else:
			xtype = a_type
295
		if a_mode == 'i':
Guido van Rossum's avatar
Guido van Rossum committed
296 297 298 299 300 301 302
			#
			# Implicit argument;
			# a_factor is divisor if present,
			# a_sub indicates which arg (`database index`)
			#
			j = eval(a_sub)
			print '\tif',
303
			print '(!geti' + xtype + 'arraysize(args,',
Guido van Rossum's avatar
Guido van Rossum committed
304 305
			print `n_in_args` + ',',
			print `in_pos[j]` + ',',
306 307
			if xtype <> a_type:
				print '('+xtype+' *)',
Guido van Rossum's avatar
Guido van Rossum committed
308 309 310 311 312 313
			print '&arg' + `i+1` + '))'
			print '\t\treturn NULL;'
			if a_factor:
				print '\targ' + `i+1`,
				print '= arg' + `i+1`,
				print '/', a_factor + ';'
314
		elif a_mode == 's':
315 316
			if a_sub and not isnum(a_sub):
				# Allocate memory for varsize array
Guido van Rossum's avatar
Guido van Rossum committed
317
				print '\tif ((arg' + `i+1`, '=',
318 319
				if a_factor:
					print '('+a_type+'(*)['+a_factor+'])',
Guido van Rossum's avatar
Guido van Rossum committed
320
				print 'PyMem_NEW(' + a_type, ',',
321 322
				if a_factor:
					print a_factor, '*',
Guido van Rossum's avatar
Guido van Rossum committed
323
				print a_sub, ')) == NULL)'
Guido van Rossum's avatar
Guido van Rossum committed
324
				print '\t\treturn PyErr_NoMemory();'
Guido van Rossum's avatar
Guido van Rossum committed
325 326
			print '\tif',
			if a_factor or a_sub: # Get a fixed-size array array
327
				print '(!geti' + xtype + 'array(args,',
Guido van Rossum's avatar
Guido van Rossum committed
328 329 330 331 332
				print `n_in_args` + ',',
				print `in_pos[i]` + ',',
				if a_factor: print a_factor,
				if a_factor and a_sub: print '*',
				if a_sub: print a_sub,
333 334 335 336
				print ',',
				if (a_sub and a_factor) or xtype <> a_type:
					print '('+xtype+' *)',
				print 'arg' + `i+1` + '))'
Guido van Rossum's avatar
Guido van Rossum committed
337
			else: # Get a simple variable
338
				print '(!geti' + xtype + 'arg(args,',
Guido van Rossum's avatar
Guido van Rossum committed
339 340
				print `n_in_args` + ',',
				print `in_pos[i]` + ',',
341 342
				if xtype <> a_type:
					print '('+xtype+' *)',
Guido van Rossum's avatar
Guido van Rossum committed
343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
				print '&arg' + `i+1` + '))'
			print '\t\treturn NULL;'
	#
	# Begin of function call
	#
	if type <> 'void':
		print '\tretval =', func + '(',
	else:
		print '\t' + func + '(',
	#
	# Argument list
	#
	for i in range(len(database)):
		if i > 0: print ',',
		a_type, a_mode, a_factor, a_sub = database[i]
358
		if a_mode == 'r' and not a_factor:
Guido van Rossum's avatar
Guido van Rossum committed
359 360 361 362 363 364 365 366 367 368 369
			print '&',
		print 'arg' + `i+1`,
	#
	# End of function call
	#
	print ');'
	#
	# Free varsize arrays
	#
	for i in range(len(database)):
		a_type, a_mode, a_factor, a_sub = database[i]
370
		if a_mode == 's' and a_sub and not isnum(a_sub):
Guido van Rossum's avatar
Guido van Rossum committed
371
			print '\tPyMem_DEL(arg' + `i+1` + ');'
Guido van Rossum's avatar
Guido van Rossum committed
372 373 374 375 376 377 378 379 380
	#
	# Return
	#
	if n_out_args:
		#
		# Multiple return values -- construct a tuple
		#
		if type <> 'void':
			n_out_args = n_out_args + 1
381
		if n_out_args == 1:
Guido van Rossum's avatar
Guido van Rossum committed
382 383
			for i in range(len(database)):
				a_type, a_mode, a_factor, a_sub = database[i]
384
				if a_mode == 'r':
Guido van Rossum's avatar
Guido van Rossum committed
385 386 387 388 389 390
					break
			else:
				raise arg_error, 'expected r arg not found'
			print '\treturn',
			print mkobject(a_type, 'arg' + `i+1`) + ';'
		else:
Guido van Rossum's avatar
Guido van Rossum committed
391
			print '\t{ PyObject *v = PyTuple_New(',
Guido van Rossum's avatar
Guido van Rossum committed
392 393 394 395
			print n_out_args, ');'
			print '\t  if (v == NULL) return NULL;'
			i_out = 0
			if type <> 'void':
Guido van Rossum's avatar
Guido van Rossum committed
396
				print '\t  PyTuple_SetItem(v,',
Guido van Rossum's avatar
Guido van Rossum committed
397 398 399 400 401
				print `i_out` + ',',
				print mkobject(type, 'retval') + ');'
				i_out = i_out + 1
			for i in range(len(database)):
				a_type, a_mode, a_factor, a_sub = database[i]
402
				if a_mode == 'r':
Guido van Rossum's avatar
Guido van Rossum committed
403
					print '\t  PyTuple_SetItem(v,',
Guido van Rossum's avatar
Guido van Rossum committed
404 405 406 407 408 409 410 411 412 413 414
					print `i_out` + ',',
					s = mkobject(a_type, 'arg' + `i+1`)
					print s + ');'
					i_out = i_out + 1
			print '\t  return v;'
			print '\t}'
	else:
		#
		# Simple function return
		# Return None or return value
		#
415
		if type == 'void':
Guido van Rossum's avatar
Guido van Rossum committed
416 417
			print '\tPy_INCREF(Py_None);'
			print '\treturn Py_None;'
Guido van Rossum's avatar
Guido van Rossum committed
418 419 420 421 422 423 424 425 426 427 428
		else:
			print '\treturn', mkobject(type, 'retval') + ';'
	#
	# Stub body closing brace
	#
	print '}'


# Subroutine to return a function call to mknew<type>object(<arg>)
#
def mkobject(type, arg):
429 430 431
	if type[:9] == 'unsigned ':
		type = type[9:]
		return 'mknew' + type + 'object((' + type + ') ' + arg + ')'
Guido van Rossum's avatar
Guido van Rossum committed
432 433 434
	return 'mknew' + type + 'object(' + arg + ')'


435 436 437 438 439 440 441 442 443
defined_archs = []

# usage: cgen [ -Dmach ... ] [ file ]
for arg in sys.argv[1:]:
	if arg[:2] == '-D':
		defined_archs.append(arg[2:])
	else:
		# Open optional file argument
		sys.stdin = open(arg, 'r')
444 445


Guido van Rossum's avatar
Guido van Rossum committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
# Input line number
lno = 0


# Input is divided in two parts, separated by a line containing '%%'.
#	<part1>		-- literally copied to stdout
#	<part2>		-- stub definitions

# Variable indicating the current input part.
#
part = 1

# Main loop over the input
#
while 1:
	try:
		line = raw_input()
	except EOFError:
		break
	#
	lno = lno+1
	words = string.split(line)
	#
469
	if part == 1:
Guido van Rossum's avatar
Guido van Rossum committed
470 471 472 473
		#
		# In part 1, copy everything literally
		# except look for a line of just '%%'
		#
474
		if words == ['%%']:
Guido van Rossum's avatar
Guido van Rossum committed
475 476 477 478 479 480 481 482
			part = part + 1
		else:
			#
			# Look for names of manually written
			# stubs: a single percent followed by the name
			# of the function in Python.
			# The stub name is derived by prefixing 'gl_'.
			#
483
			if words and words[0][0] == '%':
Guido van Rossum's avatar
Guido van Rossum committed
484 485 486 487 488 489 490
				func = words[0][1:]
				if (not func) and words[1:]:
					func = words[1]
				if func:
					functions.append(func)
			else:
				print line
491 492 493 494 495 496 497 498 499 500 501 502 503
		continue
	if not words:
		continue		# skip empty line
	elif words[0] == 'if':
		# if XXX rest
		# if !XXX rest
		if words[1][0] == '!':
			if words[1][1:] in defined_archs:
				continue
		elif words[1] not in defined_archs:
			continue
		words = words[2:]
	if words[0] == '#include':
Guido van Rossum's avatar
Guido van Rossum committed
504
		print line
505
	elif words[0][:1] == '#':
Guido van Rossum's avatar
Guido van Rossum committed
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
		pass			# ignore comment
	elif words[0] not in return_types:
		err('Line', lno, ': bad return type :', words[0])
	elif len(words) < 2:
		err('Line', lno, ': no funcname :', line)
	else:
		if len(words) % 2 <> 0:
			err('Line', lno, ': odd argument list :', words[2:])
		else:
			database = []
			try:
				for i in range(2, len(words), 2):
					x = checkarg(words[i], words[i+1])
					database.append(x)
				print
				print '/*',
				for w in words: print w,
				print '*/'
				generate(words[0], words[1], database)
			except arg_error, msg:
				err('Line', lno, ':', msg)


print
Guido van Rossum's avatar
Guido van Rossum committed
530
print 'static struct PyMethodDef gl_methods[] = {'
Guido van Rossum's avatar
Guido van Rossum committed
531 532 533 534 535
for func in functions:
	print '\t{"' + func + '", gl_' + func + '},'
print '\t{NULL, NULL} /* Sentinel */'
print '};'
print
536
print 'void'
Guido van Rossum's avatar
Guido van Rossum committed
537 538
print 'initgl()'
print '{'
Guido van Rossum's avatar
Guido van Rossum committed
539
print '\t(void) Py_InitModule("gl", gl_methods);'
Guido van Rossum's avatar
Guido van Rossum committed
540
print '}'