blob: 539cc28fffc1cdf3485059af466f8e9f98a9afba [file] [log] [blame]
Daniel Dunbara83fb862009-01-15 04:24:17 +00001#!/usr/bin/python
2
3from pprint import pprint
4import random, atexit, time
5from random import randrange
Daniel Dunbar0f1730d2009-02-22 04:17:53 +00006import re
Daniel Dunbara83fb862009-01-15 04:24:17 +00007
8from Enumeration import *
9from TypeGen import *
10
11####
12
13class TypePrinter:
14 def __init__(self, output, outputHeader=None,
15 outputTests=None, outputDriver=None,
16 headerName=None, info=None):
17 self.output = output
18 self.outputHeader = outputHeader
19 self.outputTests = outputTests
20 self.outputDriver = outputDriver
21 self.writeBody = outputHeader or outputTests or outputDriver
22 self.types = {}
23 self.testValues = {}
24 self.testReturnValues = {}
Daniel Dunbar5ce61572009-01-28 02:01:23 +000025 self.layoutTests = []
Daniel Dunbara83fb862009-01-15 04:24:17 +000026
27 if info:
28 for f in (self.output,self.outputHeader,self.outputTests,self.outputDriver):
29 if f:
30 print >>f,info
31
32 if self.writeBody:
33 print >>self.output, '#include <stdio.h>\n'
34 if self.outputTests:
Daniel Dunbar9dd60b42009-02-17 23:13:43 +000035 print >>self.outputTests, '#include <stdio.h>'
36 print >>self.outputTests, '#include <string.h>'
37 print >>self.outputTests, '#include <assert.h>\n'
Daniel Dunbara83fb862009-01-15 04:24:17 +000038
39 if headerName:
40 for f in (self.output,self.outputTests,self.outputDriver):
41 if f is not None:
42 print >>f, '#include "%s"\n'%(headerName,)
43
44 if self.outputDriver:
Daniel Dunbar9dd60b42009-02-17 23:13:43 +000045 print >>self.outputDriver, '#include <stdio.h>\n'
Daniel Dunbara83fb862009-01-15 04:24:17 +000046 print >>self.outputDriver, 'int main(int argc, char **argv) {'
47
48 def finish(self):
Daniel Dunbar5ce61572009-01-28 02:01:23 +000049 if self.layoutTests:
50 print >>self.output, 'int main(int argc, char **argv) {'
51 for f in self.layoutTests:
52 print >>self.output, ' %s();' % f
53 print >>self.output, ' return 0;'
54 print >>self.output, '}'
55
Daniel Dunbara83fb862009-01-15 04:24:17 +000056 if self.outputDriver:
Daniel Dunbar9dd60b42009-02-17 23:13:43 +000057 print >>self.outputDriver, ' printf("DONE\\n");'
Daniel Dunbara83fb862009-01-15 04:24:17 +000058 print >>self.outputDriver, ' return 0;'
Daniel Dunbar5ce61572009-01-28 02:01:23 +000059 print >>self.outputDriver, '}'
Daniel Dunbara83fb862009-01-15 04:24:17 +000060
61 def getTypeName(self, T):
62 if isinstance(T,BuiltinType):
63 return T.name
64 name = self.types.get(T)
65 if name is None:
66 name = 'T%d'%(len(self.types),)
67 # Reserve slot
68 self.types[T] = None
69 if self.outputHeader:
70 print >>self.outputHeader,T.getTypedefDef(name, self)
71 else:
72 print >>self.output,T.getTypedefDef(name, self)
73 if self.outputTests:
74 print >>self.outputTests,T.getTypedefDef(name, self)
75 self.types[T] = name
76 return name
77
Daniel Dunbar5ce61572009-01-28 02:01:23 +000078 def writeLayoutTest(self, i, ty):
79 tyName = self.getTypeName(ty)
80 tyNameClean = tyName.replace(' ','_').replace('*','star')
81 fnName = 'test_%s' % tyNameClean
82
83 print >>self.output,'void %s(void) {' % fnName
84 self.printSizeOfType(' %s'%fnName, tyName, ty, self.output)
85 self.printAlignOfType(' %s'%fnName, tyName, ty, self.output)
86 self.printOffsetsOfType(' %s'%fnName, tyName, ty, self.output)
87 print >>self.output,'}'
88 print >>self.output
89
90 self.layoutTests.append(fnName)
91
Daniel Dunbara83fb862009-01-15 04:24:17 +000092 def writeFunction(self, i, FT):
93 args = ', '.join(['%s arg%d'%(self.getTypeName(t),i) for i,t in enumerate(FT.argTypes)])
94 if not args:
95 args = 'void'
96
97 if FT.returnType is None:
98 retvalName = None
99 retvalTypeName = 'void'
100 else:
101 retvalTypeName = self.getTypeName(FT.returnType)
102 if self.writeBody or self.outputTests:
103 retvalName = self.getTestReturnValue(FT.returnType)
104
105 fnName = 'fn%d'%(FT.index,)
106 if self.outputHeader:
107 print >>self.outputHeader,'%s %s(%s);'%(retvalTypeName, fnName, args)
108 elif self.outputTests:
109 print >>self.outputTests,'%s %s(%s);'%(retvalTypeName, fnName, args)
110
111 print >>self.output,'%s %s(%s)'%(retvalTypeName, fnName, args),
112 if self.writeBody:
113 print >>self.output, '{'
114
115 for i,t in enumerate(FT.argTypes):
116 self.printValueOfType(' %s'%fnName, 'arg%d'%i, t)
117
118 if retvalName is not None:
119 print >>self.output, ' return %s;'%(retvalName,)
120 print >>self.output, '}'
121 else:
122 print >>self.output, '{}'
123 print >>self.output
124
125 if self.outputDriver:
126 print >>self.outputDriver, ' { extern void test_%s(void); test_%s(); }\n'%(fnName,fnName,)
127
128 if self.outputTests:
129 if self.outputHeader:
130 print >>self.outputHeader, 'void test_%s(void);'%(fnName,)
131
132 if retvalName is None:
133 retvalTests = None
134 else:
135 retvalTests = self.getTestValuesArray(FT.returnType)
136 tests = map(self.getTestValuesArray, FT.argTypes)
137 print >>self.outputTests, 'void test_%s(void) {'%(fnName,)
138
139 if retvalTests is not None:
140 print >>self.outputTests, ' printf("%s: testing return.\\n");'%(fnName,)
141 print >>self.outputTests, ' for (int i=0; i<%d; ++i) {'%(retvalTests[1],)
142 args = ', '.join(['%s[%d]'%(t,randrange(l)) for t,l in tests])
143 print >>self.outputTests, ' %s RV;'%(retvalTypeName,)
144 print >>self.outputTests, ' %s = %s[i];'%(retvalName, retvalTests[0])
145 print >>self.outputTests, ' RV = %s(%s);'%(fnName, args)
146 self.printValueOfType(' %s_RV'%fnName, 'RV', FT.returnType, output=self.outputTests, indent=4)
Daniel Dunbar9dd60b42009-02-17 23:13:43 +0000147 self.checkTypeValues('RV', '%s[i]' % retvalTests[0], FT.returnType, output=self.outputTests, indent=4)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000148 print >>self.outputTests, ' }'
149
150 if tests:
151 print >>self.outputTests, ' printf("%s: testing arguments.\\n");'%(fnName,)
152 for i,(array,length) in enumerate(tests):
153 for j in range(length):
154 args = ['%s[%d]'%(t,randrange(l)) for t,l in tests]
155 args[i] = '%s[%d]'%(array,j)
156 print >>self.outputTests, ' %s(%s);'%(fnName, ', '.join(args),)
157 print >>self.outputTests, '}'
158
159 def getTestReturnValue(self, type):
160 typeName = self.getTypeName(type)
161 info = self.testReturnValues.get(typeName)
162 if info is None:
163 name = '%s_retval'%(typeName.replace(' ','_').replace('*','star'),)
164 print >>self.output, '%s %s;'%(typeName,name)
165 if self.outputHeader:
166 print >>self.outputHeader, 'extern %s %s;'%(typeName,name)
167 elif self.outputTests:
168 print >>self.outputTests, 'extern %s %s;'%(typeName,name)
169 info = self.testReturnValues[typeName] = name
170 return info
171
172 def getTestValuesArray(self, type):
173 typeName = self.getTypeName(type)
174 info = self.testValues.get(typeName)
175 if info is None:
176 name = '%s_values'%(typeName.replace(' ','_').replace('*','star'),)
177 print >>self.outputTests, 'static %s %s[] = {'%(typeName,name)
178 length = 0
179 for item in self.getTestValues(type):
180 print >>self.outputTests, '\t%s,'%(item,)
181 length += 1
182 print >>self.outputTests,'};'
183 info = self.testValues[typeName] = (name,length)
184 return info
185
186 def getTestValues(self, t):
187 if isinstance(t, BuiltinType):
188 if t.name=='float':
189 for i in ['0.0','-1.0','1.0']:
190 yield i+'f'
191 elif t.name=='double':
192 for i in ['0.0','-1.0','1.0']:
193 yield i
194 elif t.name in ('void *'):
195 yield '(void*) 0'
196 yield '(void*) -1'
197 else:
198 yield '(%s) 0'%(t.name,)
199 yield '(%s) -1'%(t.name,)
200 yield '(%s) 1'%(t.name,)
201 elif isinstance(t, RecordType):
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000202 nonPadding = [f for f in t.fields
203 if not f.isPaddingBitField()]
204
205 if not nonPadding:
Daniel Dunbara83fb862009-01-15 04:24:17 +0000206 yield '{ }'
Daniel Dunbar900ed552009-01-29 07:36:46 +0000207 return
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000208
Daniel Dunbar900ed552009-01-29 07:36:46 +0000209 # FIXME: Use designated initializers to access non-first
210 # fields of unions.
211 if t.isUnion:
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000212 for v in self.getTestValues(nonPadding[0]):
213 yield '{ %s }' % v
Daniel Dunbar900ed552009-01-29 07:36:46 +0000214 return
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000215
216 fieldValues = map(list, map(self.getTestValues, nonPadding))
Daniel Dunbara83fb862009-01-15 04:24:17 +0000217 for i,values in enumerate(fieldValues):
218 for v in values:
219 elements = map(random.choice,fieldValues)
220 elements[i] = v
221 yield '{ %s }'%(', '.join(elements))
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000222
Daniel Dunbara83fb862009-01-15 04:24:17 +0000223 elif isinstance(t, ComplexType):
224 for t in self.getTestValues(t.elementType):
Daniel Dunbar550faa32009-01-26 19:05:20 +0000225 yield '%s + %s * 1i'%(t,t)
226 elif isinstance(t, ArrayType):
Daniel Dunbara83fb862009-01-15 04:24:17 +0000227 values = list(self.getTestValues(t.elementType))
228 if not values:
229 yield '{ }'
Daniel Dunbar550faa32009-01-26 19:05:20 +0000230 for i in range(t.numElements):
Daniel Dunbara83fb862009-01-15 04:24:17 +0000231 for v in values:
Daniel Dunbar550faa32009-01-26 19:05:20 +0000232 elements = [random.choice(values) for i in range(t.numElements)]
Daniel Dunbara83fb862009-01-15 04:24:17 +0000233 elements[i] = v
234 yield '{ %s }'%(', '.join(elements))
235 else:
236 raise NotImplementedError,'Cannot make tests values of type: "%s"'%(t,)
237
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000238 def printSizeOfType(self, prefix, name, t, output=None, indent=2):
239 print >>output, '%*sprintf("%s: sizeof(%s) = %%ld\\n", sizeof(%s));'%(indent, '', prefix, name, name)
240 def printAlignOfType(self, prefix, name, t, output=None, indent=2):
241 print >>output, '%*sprintf("%s: __alignof__(%s) = %%ld\\n", __alignof__(%s));'%(indent, '', prefix, name, name)
242 def printOffsetsOfType(self, prefix, name, t, output=None, indent=2):
243 if isinstance(t, RecordType):
244 for i,f in enumerate(t.fields):
Daniel Dunbar122ed242009-05-07 23:19:55 +0000245 if f.isPaddingBitField():
246 continue
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000247 fname = 'field%d' % i
248 print >>output, '%*sprintf("%s: __builtin_offsetof(%s, %s) = %%ld\\n", __builtin_offsetof(%s, %s));'%(indent, '', prefix, name, fname, name, fname)
249
Daniel Dunbara83fb862009-01-15 04:24:17 +0000250 def printValueOfType(self, prefix, name, t, output=None, indent=2):
251 if output is None:
252 output = self.output
253 if isinstance(t, BuiltinType):
254 if t.name.endswith('long long'):
255 code = 'lld'
256 elif t.name.endswith('long'):
257 code = 'ld'
258 elif t.name.split(' ')[-1] in ('_Bool','char','short','int'):
259 code = 'd'
260 elif t.name in ('float','double'):
261 code = 'f'
262 elif t.name == 'long double':
263 code = 'Lf'
264 else:
265 code = 'p'
266 print >>output, '%*sprintf("%s: %s = %%%s\\n", %s);'%(indent, '', prefix, name, code, name)
267 elif isinstance(t, RecordType):
268 if not t.fields:
269 print >>output, '%*sprintf("%s: %s (empty)\\n");'%(indent, '', prefix, name)
270 for i,f in enumerate(t.fields):
Daniel Dunbar122ed242009-05-07 23:19:55 +0000271 if f.isPaddingBitField():
272 continue
Daniel Dunbara83fb862009-01-15 04:24:17 +0000273 fname = '%s.field%d'%(name,i)
274 self.printValueOfType(prefix, fname, f, output=output, indent=indent)
275 elif isinstance(t, ComplexType):
276 self.printValueOfType(prefix, '(__real %s)'%name, t.elementType, output=output,indent=indent)
277 self.printValueOfType(prefix, '(__imag %s)'%name, t.elementType, output=output,indent=indent)
Daniel Dunbar550faa32009-01-26 19:05:20 +0000278 elif isinstance(t, ArrayType):
279 for i in range(t.numElements):
280 # Access in this fashion as a hackish way to portably
281 # access vectors.
Daniel Dunbare61e95f2009-01-29 08:48:06 +0000282 if t.isVector:
283 self.printValueOfType(prefix, '((%s*) &%s)[%d]'%(t.elementType,name,i), t.elementType, output=output,indent=indent)
284 else:
285 self.printValueOfType(prefix, '%s[%d]'%(name,i), t.elementType, output=output,indent=indent)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000286 else:
287 raise NotImplementedError,'Cannot print value of type: "%s"'%(t,)
288
Daniel Dunbar9dd60b42009-02-17 23:13:43 +0000289 def checkTypeValues(self, nameLHS, nameRHS, t, output=None, indent=2):
290 prefix = 'foo'
291 if output is None:
292 output = self.output
293 if isinstance(t, BuiltinType):
294 print >>output, '%*sassert(%s == %s);' % (indent, '', nameLHS, nameRHS)
295 elif isinstance(t, RecordType):
296 for i,f in enumerate(t.fields):
Daniel Dunbar122ed242009-05-07 23:19:55 +0000297 if f.isPaddingBitField():
298 continue
Daniel Dunbar9dd60b42009-02-17 23:13:43 +0000299 self.checkTypeValues('%s.field%d'%(nameLHS,i), '%s.field%d'%(nameRHS,i),
300 f, output=output, indent=indent)
301 if t.isUnion:
302 break
303 elif isinstance(t, ComplexType):
304 self.checkTypeValues('(__real %s)'%nameLHS, '(__real %s)'%nameRHS, t.elementType, output=output,indent=indent)
305 self.checkTypeValues('(__imag %s)'%nameLHS, '(__imag %s)'%nameRHS, t.elementType, output=output,indent=indent)
306 elif isinstance(t, ArrayType):
307 for i in range(t.numElements):
308 # Access in this fashion as a hackish way to portably
309 # access vectors.
310 if t.isVector:
311 self.checkTypeValues('((%s*) &%s)[%d]'%(t.elementType,nameLHS,i),
312 '((%s*) &%s)[%d]'%(t.elementType,nameRHS,i),
313 t.elementType, output=output,indent=indent)
314 else:
315 self.checkTypeValues('%s[%d]'%(nameLHS,i), '%s[%d]'%(nameRHS,i),
316 t.elementType, output=output,indent=indent)
317 else:
318 raise NotImplementedError,'Cannot print value of type: "%s"'%(t,)
319
Daniel Dunbara83fb862009-01-15 04:24:17 +0000320import sys
321
322def main():
323 from optparse import OptionParser, OptionGroup
324 parser = OptionParser("%prog [options] {indices}")
325 parser.add_option("", "--mode", dest="mode",
326 help="autogeneration mode (random or linear) [default %default]",
327 type='choice', choices=('random','linear'), default='linear')
328 parser.add_option("", "--count", dest="count",
329 help="autogenerate COUNT functions according to MODE",
330 type=int, default=0)
331 parser.add_option("", "--min", dest="minIndex", metavar="N",
332 help="start autogeneration with the Nth function type [default %default]",
333 type=int, default=0)
334 parser.add_option("", "--max", dest="maxIndex", metavar="N",
335 help="maximum index for random autogeneration [default %default]",
336 type=int, default=10000000)
337 parser.add_option("", "--seed", dest="seed",
338 help="random number generator seed [default %default]",
339 type=int, default=1)
340 parser.add_option("", "--use-random-seed", dest="useRandomSeed",
341 help="use random value for initial random number generator seed",
342 action='store_true', default=False)
343 parser.add_option("-o", "--output", dest="output", metavar="FILE",
344 help="write output to FILE [default %default]",
345 type=str, default='-')
346 parser.add_option("-O", "--output-header", dest="outputHeader", metavar="FILE",
347 help="write header file for output to FILE [default %default]",
348 type=str, default=None)
349 parser.add_option("-T", "--output-tests", dest="outputTests", metavar="FILE",
350 help="write function tests to FILE [default %default]",
351 type=str, default=None)
352 parser.add_option("-D", "--output-driver", dest="outputDriver", metavar="FILE",
353 help="write test driver to FILE [default %default]",
354 type=str, default=None)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000355 parser.add_option("", "--test-layout", dest="testLayout", metavar="FILE",
356 help="test structure layout",
357 action='store_true', default=False)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000358
359 group = OptionGroup(parser, "Type Enumeration Options")
360 # Builtins - Ints
361 group.add_option("", "--no-char", dest="useChar",
362 help="do not generate char types",
363 action="store_false", default=True)
364 group.add_option("", "--no-short", dest="useShort",
365 help="do not generate short types",
366 action="store_false", default=True)
367 group.add_option("", "--no-int", dest="useInt",
368 help="do not generate int types",
369 action="store_false", default=True)
370 group.add_option("", "--no-long", dest="useLong",
371 help="do not generate long types",
372 action="store_false", default=True)
373 group.add_option("", "--no-long-long", dest="useLongLong",
374 help="do not generate long long types",
375 action="store_false", default=True)
376 group.add_option("", "--no-unsigned", dest="useUnsigned",
377 help="do not generate unsigned integer types",
378 action="store_false", default=True)
379
380 # Other builtins
381 group.add_option("", "--no-bool", dest="useBool",
382 help="do not generate bool types",
383 action="store_false", default=True)
384 group.add_option("", "--no-float", dest="useFloat",
385 help="do not generate float types",
386 action="store_false", default=True)
387 group.add_option("", "--no-double", dest="useDouble",
388 help="do not generate double types",
389 action="store_false", default=True)
390 group.add_option("", "--no-long-double", dest="useLongDouble",
391 help="do not generate long double types",
392 action="store_false", default=True)
393 group.add_option("", "--no-void-pointer", dest="useVoidPointer",
394 help="do not generate void* types",
395 action="store_false", default=True)
396
397 # Derived types
398 group.add_option("", "--no-array", dest="useArray",
399 help="do not generate record types",
400 action="store_false", default=True)
401 group.add_option("", "--no-complex", dest="useComplex",
402 help="do not generate complex types",
403 action="store_false", default=True)
404 group.add_option("", "--no-record", dest="useRecord",
405 help="do not generate record types",
406 action="store_false", default=True)
407 group.add_option("", "--no-union", dest="recordUseUnion",
408 help="do not generate union types",
409 action="store_false", default=True)
410 group.add_option("", "--no-vector", dest="useVector",
411 help="do not generate vector types",
412 action="store_false", default=True)
Daniel Dunbar122ed242009-05-07 23:19:55 +0000413 group.add_option("", "--no-bit-field", dest="useBitField",
414 help="do not generate bit-field record members",
415 action="store_false", default=True)
416 group.add_option("", "--no-builtins", dest="useBuiltins",
417 help="do not use any types",
418 action="store_false", default=True)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000419
420 # Tuning
421 group.add_option("", "--no-function-return", dest="functionUseReturn",
422 help="do not generate return types for functions",
423 action="store_false", default=True)
Daniel Dunbar0f1730d2009-02-22 04:17:53 +0000424 group.add_option("", "--vector-types", dest="vectorTypes",
425 help="comma separated list of vector types (e.g., v2i32) [default %default]",
Daniel Dunbarec1abb92009-03-02 06:14:33 +0000426 action="store", type=str, default='v2i16, v1i64, v2i32, v4i16, v8i8, v2f32, v2i64, v4i32, v8i16, v16i8, v2f64, v4f32, v16f32', metavar="N")
Daniel Dunbar122ed242009-05-07 23:19:55 +0000427 group.add_option("", "--bit-fields", dest="bitFields",
428 help="comma separated list 'type:width' bit-field specifiers [default %default]",
Daniel Dunbar238a3182009-05-08 20:10:52 +0000429 action="store", type=str, default="char:0,char:4,unsigned:0,unsigned:4,unsigned:13,unsigned:24")
Daniel Dunbara83fb862009-01-15 04:24:17 +0000430 group.add_option("", "--max-args", dest="functionMaxArgs",
431 help="maximum number of arguments per function [default %default]",
432 action="store", type=int, default=4, metavar="N")
433 group.add_option("", "--max-array", dest="arrayMaxSize",
434 help="maximum array size [default %default]",
435 action="store", type=int, default=4, metavar="N")
436 group.add_option("", "--max-record", dest="recordMaxSize",
437 help="maximum number of fields per record [default %default]",
438 action="store", type=int, default=4, metavar="N")
439 group.add_option("", "--max-record-depth", dest="recordMaxDepth",
440 help="maximum nested structure depth [default %default]",
441 action="store", type=int, default=None, metavar="N")
442 parser.add_option_group(group)
443 (opts, args) = parser.parse_args()
444
445 if not opts.useRandomSeed:
446 random.seed(opts.seed)
447
448 # Contruct type generator
449 builtins = []
Daniel Dunbar122ed242009-05-07 23:19:55 +0000450 if opts.useBuiltins:
451 ints = []
452 if opts.useChar: ints.append(('char',1))
453 if opts.useShort: ints.append(('short',2))
454 if opts.useInt: ints.append(('int',4))
455 # FIXME: Wrong size.
456 if opts.useLong: ints.append(('long',4))
457 if opts.useLongLong: ints.append(('long long',8))
458 if opts.useUnsigned:
459 ints = ([('unsigned %s'%i,s) for i,s in ints] +
460 [('signed %s'%i,s) for i,s in ints])
461 builtins.extend(ints)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000462
Daniel Dunbar122ed242009-05-07 23:19:55 +0000463 if opts.useBool: builtins.append(('_Bool',1))
464 if opts.useFloat: builtins.append(('float',4))
465 if opts.useDouble: builtins.append(('double',8))
466 if opts.useLongDouble: builtins.append(('long double',16))
467 # FIXME: Wrong size.
468 if opts.useVoidPointer: builtins.append(('void*',4))
Daniel Dunbara83fb862009-01-15 04:24:17 +0000469
Daniel Dunbar550faa32009-01-26 19:05:20 +0000470 btg = FixedTypeGenerator([BuiltinType(n,s) for n,s in builtins])
Daniel Dunbar122ed242009-05-07 23:19:55 +0000471
472 bitfields = []
473 for specifier in opts.bitFields.split(','):
474 if not specifier.strip():
475 continue
476 name,width = specifier.strip().split(':', 1)
477 bitfields.append(BuiltinType(name,None,int(width)))
478 bftg = FixedTypeGenerator(bitfields)
479
Daniel Dunbar0f1730d2009-02-22 04:17:53 +0000480 charType = BuiltinType('char',1)
481 shortType = BuiltinType('short',2)
482 intType = BuiltinType('int',4)
483 longlongType = BuiltinType('long long',8)
484 floatType = BuiltinType('float',4)
485 doubleType = BuiltinType('double',8)
486 sbtg = FixedTypeGenerator([charType, intType, floatType, doubleType])
Daniel Dunbara83fb862009-01-15 04:24:17 +0000487
488 atg = AnyTypeGenerator()
489 artg = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000490 def makeGenerator(atg, subgen, subfieldgen, useRecord, useArray, useBitField):
Daniel Dunbara83fb862009-01-15 04:24:17 +0000491 atg.addGenerator(btg)
Daniel Dunbar122ed242009-05-07 23:19:55 +0000492 if useBitField and opts.useBitField:
493 atg.addGenerator(bftg)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000494 if useRecord and opts.useRecord:
495 assert subgen
Daniel Dunbar122ed242009-05-07 23:19:55 +0000496 atg.addGenerator(RecordTypeGenerator(subfieldgen, opts.recordUseUnion,
Daniel Dunbara83fb862009-01-15 04:24:17 +0000497 opts.recordMaxSize))
498 if opts.useComplex:
499 # FIXME: Allow overriding builtins here
500 atg.addGenerator(ComplexTypeGenerator(sbtg))
501 if useArray and opts.useArray:
502 assert subgen
503 atg.addGenerator(ArrayTypeGenerator(subgen, opts.arrayMaxSize))
504 if opts.useVector:
Daniel Dunbar0f1730d2009-02-22 04:17:53 +0000505 vTypes = []
506 for i,t in enumerate(opts.vectorTypes.split(',')):
507 m = re.match('v([1-9][0-9]*)([if][1-9][0-9]*)', t.strip())
508 if not m:
509 parser.error('Invalid vector type: %r' % t)
510 count,kind = m.groups()
511 count = int(count)
512 type = { 'i8' : charType,
513 'i16' : shortType,
514 'i32' : intType,
515 'i64' : longlongType,
516 'f32' : floatType,
517 'f64' : doubleType,
518 }.get(kind)
519 if not type:
520 parser.error('Invalid vector type: %r' % t)
521 vTypes.append(ArrayType(i, True, type, count * type.size))
522
523 atg.addGenerator(FixedTypeGenerator(vTypes))
Daniel Dunbara83fb862009-01-15 04:24:17 +0000524
525 if opts.recordMaxDepth is None:
526 # Fully recursive, just avoid top-level arrays.
Daniel Dunbar122ed242009-05-07 23:19:55 +0000527 subFTG = AnyTypeGenerator()
Daniel Dunbara83fb862009-01-15 04:24:17 +0000528 subTG = AnyTypeGenerator()
529 atg = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000530 makeGenerator(subFTG, atg, atg, True, True, True)
531 makeGenerator(subTG, atg, subFTG, True, True, False)
532 makeGenerator(atg, subTG, subFTG, True, False, False)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000533 else:
534 # Make a chain of type generators, each builds smaller
535 # structures.
536 base = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000537 fbase = AnyTypeGenerator()
538 makeGenerator(base, None, None, False, False, False)
539 makeGenerator(fbase, None, None, False, False, True)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000540 for i in range(opts.recordMaxDepth):
541 n = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000542 fn = AnyTypeGenerator()
543 makeGenerator(n, base, fbase, True, True, False)
544 makeGenerator(fn, base, fbase, True, True, True)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000545 base = n
Daniel Dunbar122ed242009-05-07 23:19:55 +0000546 fbase = fn
Daniel Dunbara83fb862009-01-15 04:24:17 +0000547 atg = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000548 makeGenerator(atg, base, fbase, True, False, False)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000549
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000550 if opts.testLayout:
551 ftg = atg
552 else:
553 ftg = FunctionTypeGenerator(atg, opts.functionUseReturn, opts.functionMaxArgs)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000554
555 # Override max,min,count if finite
556 if opts.maxIndex is None:
557 if ftg.cardinality is aleph0:
558 opts.maxIndex = 10000000
559 else:
560 opts.maxIndex = ftg.cardinality
561 opts.maxIndex = min(opts.maxIndex, ftg.cardinality)
562 opts.minIndex = max(0,min(opts.maxIndex-1, opts.minIndex))
563 if not opts.mode=='random':
564 opts.count = min(opts.count, opts.maxIndex-opts.minIndex)
565
566 if opts.output=='-':
567 output = sys.stdout
568 else:
569 output = open(opts.output,'w')
570 atexit.register(lambda: output.close())
571
572 outputHeader = None
573 if opts.outputHeader:
574 outputHeader = open(opts.outputHeader,'w')
575 atexit.register(lambda: outputHeader.close())
576
577 outputTests = None
578 if opts.outputTests:
579 outputTests = open(opts.outputTests,'w')
580 atexit.register(lambda: outputTests.close())
581
582 outputDriver = None
583 if opts.outputDriver:
584 outputDriver = open(opts.outputDriver,'w')
585 atexit.register(lambda: outputDriver.close())
586
587 info = ''
588 info += '// %s\n'%(' '.join(sys.argv),)
589 info += '// Generated: %s\n'%(time.strftime('%Y-%m-%d %H:%M'),)
590 info += '// Cardinality of function generator: %s\n'%(ftg.cardinality,)
591 info += '// Cardinality of type generator: %s\n'%(atg.cardinality,)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000592
593 if opts.testLayout:
594 info += '\n#include <stdio.h>'
Daniel Dunbara83fb862009-01-15 04:24:17 +0000595
596 P = TypePrinter(output,
597 outputHeader=outputHeader,
598 outputTests=outputTests,
599 outputDriver=outputDriver,
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000600 headerName=opts.outputHeader,
Daniel Dunbara83fb862009-01-15 04:24:17 +0000601 info=info)
602
603 def write(N):
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000604 try:
Daniel Dunbara83fb862009-01-15 04:24:17 +0000605 FT = ftg.get(N)
606 except RuntimeError,e:
607 if e.args[0]=='maximum recursion depth exceeded':
608 print >>sys.stderr,'WARNING: Skipped %d, recursion limit exceeded (bad arguments?)'%(N,)
609 return
610 raise
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000611 if opts.testLayout:
612 P.writeLayoutTest(N, FT)
613 else:
614 P.writeFunction(N, FT)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000615
616 if args:
617 [write(int(a)) for a in args]
618
619 for i in range(opts.count):
620 if opts.mode=='linear':
621 index = opts.minIndex + i
622 else:
623 index = opts.minIndex + int((opts.maxIndex-opts.minIndex) * random.random())
624 write(index)
625
626 P.finish()
627
628if __name__=='__main__':
629 main()
630