blob: e3f6476c48f2bdfba7165c49435f5bbbfe4de9c7 [file] [log] [blame]
Eli Friedman77a1fe92009-07-10 20:15:12 +00001#!/usr/bin/env python
Daniel Dunbara83fb862009-01-15 04:24:17 +00002
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:
Douglas Gregorc6277a02010-02-02 17:49:52 +000045 print >>self.outputDriver, '#include <stdio.h>'
46 print >>self.outputDriver, '#include <stdlib.h>\n'
Daniel Dunbara83fb862009-01-15 04:24:17 +000047 print >>self.outputDriver, 'int main(int argc, char **argv) {'
Daniel Dunbar484c7ca2009-05-08 23:40:45 +000048 print >>self.outputDriver, ' int index = -1;'
49 print >>self.outputDriver, ' if (argc > 1) index = atoi(argv[1]);'
Daniel Dunbara83fb862009-01-15 04:24:17 +000050
51 def finish(self):
Daniel Dunbar5ce61572009-01-28 02:01:23 +000052 if self.layoutTests:
53 print >>self.output, 'int main(int argc, char **argv) {'
Daniel Dunbar484c7ca2009-05-08 23:40:45 +000054 print >>self.output, ' int index = -1;'
55 print >>self.output, ' if (argc > 1) index = atoi(argv[1]);'
56 for i,f in self.layoutTests:
57 print >>self.output, ' if (index == -1 || index == %d)' % i
58 print >>self.output, ' %s();' % f
Daniel Dunbar5ce61572009-01-28 02:01:23 +000059 print >>self.output, ' return 0;'
60 print >>self.output, '}'
61
Daniel Dunbara83fb862009-01-15 04:24:17 +000062 if self.outputDriver:
Daniel Dunbar9dd60b42009-02-17 23:13:43 +000063 print >>self.outputDriver, ' printf("DONE\\n");'
Daniel Dunbara83fb862009-01-15 04:24:17 +000064 print >>self.outputDriver, ' return 0;'
Daniel Dunbar5ce61572009-01-28 02:01:23 +000065 print >>self.outputDriver, '}'
Daniel Dunbara83fb862009-01-15 04:24:17 +000066
67 def getTypeName(self, T):
68 if isinstance(T,BuiltinType):
69 return T.name
70 name = self.types.get(T)
71 if name is None:
72 name = 'T%d'%(len(self.types),)
73 # Reserve slot
74 self.types[T] = None
75 if self.outputHeader:
76 print >>self.outputHeader,T.getTypedefDef(name, self)
77 else:
78 print >>self.output,T.getTypedefDef(name, self)
79 if self.outputTests:
80 print >>self.outputTests,T.getTypedefDef(name, self)
81 self.types[T] = name
82 return name
83
Daniel Dunbar5ce61572009-01-28 02:01:23 +000084 def writeLayoutTest(self, i, ty):
85 tyName = self.getTypeName(ty)
86 tyNameClean = tyName.replace(' ','_').replace('*','star')
87 fnName = 'test_%s' % tyNameClean
88
89 print >>self.output,'void %s(void) {' % fnName
90 self.printSizeOfType(' %s'%fnName, tyName, ty, self.output)
91 self.printAlignOfType(' %s'%fnName, tyName, ty, self.output)
92 self.printOffsetsOfType(' %s'%fnName, tyName, ty, self.output)
93 print >>self.output,'}'
94 print >>self.output
95
Daniel Dunbar484c7ca2009-05-08 23:40:45 +000096 self.layoutTests.append((i,fnName))
Daniel Dunbar5ce61572009-01-28 02:01:23 +000097
Daniel Dunbara83fb862009-01-15 04:24:17 +000098 def writeFunction(self, i, FT):
99 args = ', '.join(['%s arg%d'%(self.getTypeName(t),i) for i,t in enumerate(FT.argTypes)])
100 if not args:
101 args = 'void'
102
103 if FT.returnType is None:
104 retvalName = None
105 retvalTypeName = 'void'
106 else:
107 retvalTypeName = self.getTypeName(FT.returnType)
108 if self.writeBody or self.outputTests:
109 retvalName = self.getTestReturnValue(FT.returnType)
110
111 fnName = 'fn%d'%(FT.index,)
112 if self.outputHeader:
113 print >>self.outputHeader,'%s %s(%s);'%(retvalTypeName, fnName, args)
114 elif self.outputTests:
115 print >>self.outputTests,'%s %s(%s);'%(retvalTypeName, fnName, args)
116
117 print >>self.output,'%s %s(%s)'%(retvalTypeName, fnName, args),
118 if self.writeBody:
119 print >>self.output, '{'
120
121 for i,t in enumerate(FT.argTypes):
122 self.printValueOfType(' %s'%fnName, 'arg%d'%i, t)
123
124 if retvalName is not None:
125 print >>self.output, ' return %s;'%(retvalName,)
126 print >>self.output, '}'
127 else:
128 print >>self.output, '{}'
129 print >>self.output
130
131 if self.outputDriver:
Daniel Dunbar484c7ca2009-05-08 23:40:45 +0000132 print >>self.outputDriver, ' if (index == -1 || index == %d) {' % i
133 print >>self.outputDriver, ' extern void test_%s(void);' % fnName
134 print >>self.outputDriver, ' test_%s();' % fnName
135 print >>self.outputDriver, ' }'
Daniel Dunbara83fb862009-01-15 04:24:17 +0000136
137 if self.outputTests:
138 if self.outputHeader:
139 print >>self.outputHeader, 'void test_%s(void);'%(fnName,)
140
141 if retvalName is None:
142 retvalTests = None
143 else:
144 retvalTests = self.getTestValuesArray(FT.returnType)
145 tests = map(self.getTestValuesArray, FT.argTypes)
146 print >>self.outputTests, 'void test_%s(void) {'%(fnName,)
147
148 if retvalTests is not None:
149 print >>self.outputTests, ' printf("%s: testing return.\\n");'%(fnName,)
150 print >>self.outputTests, ' for (int i=0; i<%d; ++i) {'%(retvalTests[1],)
151 args = ', '.join(['%s[%d]'%(t,randrange(l)) for t,l in tests])
152 print >>self.outputTests, ' %s RV;'%(retvalTypeName,)
153 print >>self.outputTests, ' %s = %s[i];'%(retvalName, retvalTests[0])
154 print >>self.outputTests, ' RV = %s(%s);'%(fnName, args)
155 self.printValueOfType(' %s_RV'%fnName, 'RV', FT.returnType, output=self.outputTests, indent=4)
Daniel Dunbar9dd60b42009-02-17 23:13:43 +0000156 self.checkTypeValues('RV', '%s[i]' % retvalTests[0], FT.returnType, output=self.outputTests, indent=4)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000157 print >>self.outputTests, ' }'
158
159 if tests:
160 print >>self.outputTests, ' printf("%s: testing arguments.\\n");'%(fnName,)
161 for i,(array,length) in enumerate(tests):
162 for j in range(length):
163 args = ['%s[%d]'%(t,randrange(l)) for t,l in tests]
164 args[i] = '%s[%d]'%(array,j)
165 print >>self.outputTests, ' %s(%s);'%(fnName, ', '.join(args),)
166 print >>self.outputTests, '}'
167
168 def getTestReturnValue(self, type):
169 typeName = self.getTypeName(type)
170 info = self.testReturnValues.get(typeName)
171 if info is None:
172 name = '%s_retval'%(typeName.replace(' ','_').replace('*','star'),)
173 print >>self.output, '%s %s;'%(typeName,name)
174 if self.outputHeader:
175 print >>self.outputHeader, 'extern %s %s;'%(typeName,name)
176 elif self.outputTests:
177 print >>self.outputTests, 'extern %s %s;'%(typeName,name)
178 info = self.testReturnValues[typeName] = name
179 return info
180
181 def getTestValuesArray(self, type):
182 typeName = self.getTypeName(type)
183 info = self.testValues.get(typeName)
184 if info is None:
185 name = '%s_values'%(typeName.replace(' ','_').replace('*','star'),)
186 print >>self.outputTests, 'static %s %s[] = {'%(typeName,name)
187 length = 0
188 for item in self.getTestValues(type):
189 print >>self.outputTests, '\t%s,'%(item,)
190 length += 1
191 print >>self.outputTests,'};'
192 info = self.testValues[typeName] = (name,length)
193 return info
194
195 def getTestValues(self, t):
196 if isinstance(t, BuiltinType):
197 if t.name=='float':
198 for i in ['0.0','-1.0','1.0']:
199 yield i+'f'
200 elif t.name=='double':
201 for i in ['0.0','-1.0','1.0']:
202 yield i
203 elif t.name in ('void *'):
204 yield '(void*) 0'
205 yield '(void*) -1'
206 else:
207 yield '(%s) 0'%(t.name,)
208 yield '(%s) -1'%(t.name,)
209 yield '(%s) 1'%(t.name,)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000210 elif isinstance(t, EnumType):
211 for i in range(0, len(t.enumerators)):
212 yield 'enum%dval%d' % (t.index, i)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000213 elif isinstance(t, RecordType):
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000214 nonPadding = [f for f in t.fields
215 if not f.isPaddingBitField()]
216
217 if not nonPadding:
Daniel Dunbara83fb862009-01-15 04:24:17 +0000218 yield '{ }'
Daniel Dunbar900ed552009-01-29 07:36:46 +0000219 return
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000220
Daniel Dunbar900ed552009-01-29 07:36:46 +0000221 # FIXME: Use designated initializers to access non-first
222 # fields of unions.
223 if t.isUnion:
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000224 for v in self.getTestValues(nonPadding[0]):
225 yield '{ %s }' % v
Daniel Dunbar900ed552009-01-29 07:36:46 +0000226 return
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000227
228 fieldValues = map(list, map(self.getTestValues, nonPadding))
Daniel Dunbara83fb862009-01-15 04:24:17 +0000229 for i,values in enumerate(fieldValues):
230 for v in values:
231 elements = map(random.choice,fieldValues)
232 elements[i] = v
233 yield '{ %s }'%(', '.join(elements))
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000234
Daniel Dunbara83fb862009-01-15 04:24:17 +0000235 elif isinstance(t, ComplexType):
236 for t in self.getTestValues(t.elementType):
Daniel Dunbar550faa32009-01-26 19:05:20 +0000237 yield '%s + %s * 1i'%(t,t)
238 elif isinstance(t, ArrayType):
Daniel Dunbara83fb862009-01-15 04:24:17 +0000239 values = list(self.getTestValues(t.elementType))
240 if not values:
241 yield '{ }'
Daniel Dunbar550faa32009-01-26 19:05:20 +0000242 for i in range(t.numElements):
Daniel Dunbara83fb862009-01-15 04:24:17 +0000243 for v in values:
Daniel Dunbar550faa32009-01-26 19:05:20 +0000244 elements = [random.choice(values) for i in range(t.numElements)]
Daniel Dunbara83fb862009-01-15 04:24:17 +0000245 elements[i] = v
246 yield '{ %s }'%(', '.join(elements))
247 else:
248 raise NotImplementedError,'Cannot make tests values of type: "%s"'%(t,)
249
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000250 def printSizeOfType(self, prefix, name, t, output=None, indent=2):
Eli Friedman98a71702009-05-25 21:38:01 +0000251 print >>output, '%*sprintf("%s: sizeof(%s) = %%ld\\n", (long)sizeof(%s));'%(indent, '', prefix, name, name)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000252 def printAlignOfType(self, prefix, name, t, output=None, indent=2):
Eli Friedman98a71702009-05-25 21:38:01 +0000253 print >>output, '%*sprintf("%s: __alignof__(%s) = %%ld\\n", (long)__alignof__(%s));'%(indent, '', prefix, name, name)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000254 def printOffsetsOfType(self, prefix, name, t, output=None, indent=2):
255 if isinstance(t, RecordType):
256 for i,f in enumerate(t.fields):
Eli Friedman98a71702009-05-25 21:38:01 +0000257 if f.isBitField():
Daniel Dunbar122ed242009-05-07 23:19:55 +0000258 continue
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000259 fname = 'field%d' % i
Eli Friedman98a71702009-05-25 21:38:01 +0000260 print >>output, '%*sprintf("%s: __builtin_offsetof(%s, %s) = %%ld\\n", (long)__builtin_offsetof(%s, %s));'%(indent, '', prefix, name, fname, name, fname)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000261
Daniel Dunbara83fb862009-01-15 04:24:17 +0000262 def printValueOfType(self, prefix, name, t, output=None, indent=2):
263 if output is None:
264 output = self.output
265 if isinstance(t, BuiltinType):
Daniel Dunbar3dbe0b72010-09-27 20:13:19 +0000266 value_expr = name
267 if t.name.split(' ')[-1] == '_Bool':
268 # Hack to work around PR5579.
269 value_expr = "%s ? 2 : 0" % name
270
Daniel Dunbara83fb862009-01-15 04:24:17 +0000271 if t.name.endswith('long long'):
272 code = 'lld'
273 elif t.name.endswith('long'):
274 code = 'ld'
Daniel Dunbar3d2fd8d2010-09-27 20:13:22 +0000275 elif t.name.split(' ')[-1] in ('_Bool','char','short',
276 'int','unsigned'):
Daniel Dunbara83fb862009-01-15 04:24:17 +0000277 code = 'd'
278 elif t.name in ('float','double'):
279 code = 'f'
280 elif t.name == 'long double':
281 code = 'Lf'
282 else:
283 code = 'p'
Daniel Dunbar3dbe0b72010-09-27 20:13:19 +0000284 print >>output, '%*sprintf("%s: %s = %%%s\\n", %s);'%(
285 indent, '', prefix, name, code, value_expr)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000286 elif isinstance(t, EnumType):
287 print >>output, '%*sprintf("%s: %s = %%d\\n", %s);'%(indent, '', prefix, name, name)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000288 elif isinstance(t, RecordType):
289 if not t.fields:
290 print >>output, '%*sprintf("%s: %s (empty)\\n");'%(indent, '', prefix, name)
291 for i,f in enumerate(t.fields):
Daniel Dunbar122ed242009-05-07 23:19:55 +0000292 if f.isPaddingBitField():
293 continue
Daniel Dunbara83fb862009-01-15 04:24:17 +0000294 fname = '%s.field%d'%(name,i)
295 self.printValueOfType(prefix, fname, f, output=output, indent=indent)
296 elif isinstance(t, ComplexType):
297 self.printValueOfType(prefix, '(__real %s)'%name, t.elementType, output=output,indent=indent)
298 self.printValueOfType(prefix, '(__imag %s)'%name, t.elementType, output=output,indent=indent)
Daniel Dunbar550faa32009-01-26 19:05:20 +0000299 elif isinstance(t, ArrayType):
300 for i in range(t.numElements):
301 # Access in this fashion as a hackish way to portably
302 # access vectors.
Daniel Dunbare61e95f2009-01-29 08:48:06 +0000303 if t.isVector:
304 self.printValueOfType(prefix, '((%s*) &%s)[%d]'%(t.elementType,name,i), t.elementType, output=output,indent=indent)
305 else:
306 self.printValueOfType(prefix, '%s[%d]'%(name,i), t.elementType, output=output,indent=indent)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000307 else:
308 raise NotImplementedError,'Cannot print value of type: "%s"'%(t,)
309
Daniel Dunbar9dd60b42009-02-17 23:13:43 +0000310 def checkTypeValues(self, nameLHS, nameRHS, t, output=None, indent=2):
311 prefix = 'foo'
312 if output is None:
313 output = self.output
314 if isinstance(t, BuiltinType):
315 print >>output, '%*sassert(%s == %s);' % (indent, '', nameLHS, nameRHS)
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000316 elif isinstance(t, EnumType):
317 print >>output, '%*sassert(%s == %s);' % (indent, '', nameLHS, nameRHS)
Daniel Dunbar9dd60b42009-02-17 23:13:43 +0000318 elif isinstance(t, RecordType):
319 for i,f in enumerate(t.fields):
Daniel Dunbar122ed242009-05-07 23:19:55 +0000320 if f.isPaddingBitField():
321 continue
Daniel Dunbar9dd60b42009-02-17 23:13:43 +0000322 self.checkTypeValues('%s.field%d'%(nameLHS,i), '%s.field%d'%(nameRHS,i),
323 f, output=output, indent=indent)
324 if t.isUnion:
325 break
326 elif isinstance(t, ComplexType):
327 self.checkTypeValues('(__real %s)'%nameLHS, '(__real %s)'%nameRHS, t.elementType, output=output,indent=indent)
328 self.checkTypeValues('(__imag %s)'%nameLHS, '(__imag %s)'%nameRHS, t.elementType, output=output,indent=indent)
329 elif isinstance(t, ArrayType):
330 for i in range(t.numElements):
331 # Access in this fashion as a hackish way to portably
332 # access vectors.
333 if t.isVector:
334 self.checkTypeValues('((%s*) &%s)[%d]'%(t.elementType,nameLHS,i),
335 '((%s*) &%s)[%d]'%(t.elementType,nameRHS,i),
336 t.elementType, output=output,indent=indent)
337 else:
338 self.checkTypeValues('%s[%d]'%(nameLHS,i), '%s[%d]'%(nameRHS,i),
339 t.elementType, output=output,indent=indent)
340 else:
341 raise NotImplementedError,'Cannot print value of type: "%s"'%(t,)
342
Daniel Dunbara83fb862009-01-15 04:24:17 +0000343import sys
344
345def main():
346 from optparse import OptionParser, OptionGroup
347 parser = OptionParser("%prog [options] {indices}")
348 parser.add_option("", "--mode", dest="mode",
349 help="autogeneration mode (random or linear) [default %default]",
350 type='choice', choices=('random','linear'), default='linear')
351 parser.add_option("", "--count", dest="count",
352 help="autogenerate COUNT functions according to MODE",
353 type=int, default=0)
354 parser.add_option("", "--min", dest="minIndex", metavar="N",
355 help="start autogeneration with the Nth function type [default %default]",
356 type=int, default=0)
357 parser.add_option("", "--max", dest="maxIndex", metavar="N",
358 help="maximum index for random autogeneration [default %default]",
359 type=int, default=10000000)
360 parser.add_option("", "--seed", dest="seed",
361 help="random number generator seed [default %default]",
362 type=int, default=1)
363 parser.add_option("", "--use-random-seed", dest="useRandomSeed",
364 help="use random value for initial random number generator seed",
365 action='store_true', default=False)
Daniel Dunbar1ca717b2010-09-27 20:13:17 +0000366 parser.add_option("", "--skip", dest="skipTests",
367 help="add a test index to skip",
368 type=int, action='append', default=[])
Daniel Dunbara83fb862009-01-15 04:24:17 +0000369 parser.add_option("-o", "--output", dest="output", metavar="FILE",
370 help="write output to FILE [default %default]",
371 type=str, default='-')
372 parser.add_option("-O", "--output-header", dest="outputHeader", metavar="FILE",
373 help="write header file for output to FILE [default %default]",
374 type=str, default=None)
375 parser.add_option("-T", "--output-tests", dest="outputTests", metavar="FILE",
376 help="write function tests to FILE [default %default]",
377 type=str, default=None)
378 parser.add_option("-D", "--output-driver", dest="outputDriver", metavar="FILE",
379 help="write test driver to FILE [default %default]",
380 type=str, default=None)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000381 parser.add_option("", "--test-layout", dest="testLayout", metavar="FILE",
382 help="test structure layout",
383 action='store_true', default=False)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000384
385 group = OptionGroup(parser, "Type Enumeration Options")
386 # Builtins - Ints
387 group.add_option("", "--no-char", dest="useChar",
388 help="do not generate char types",
389 action="store_false", default=True)
390 group.add_option("", "--no-short", dest="useShort",
391 help="do not generate short types",
392 action="store_false", default=True)
393 group.add_option("", "--no-int", dest="useInt",
394 help="do not generate int types",
395 action="store_false", default=True)
396 group.add_option("", "--no-long", dest="useLong",
397 help="do not generate long types",
398 action="store_false", default=True)
399 group.add_option("", "--no-long-long", dest="useLongLong",
400 help="do not generate long long types",
401 action="store_false", default=True)
402 group.add_option("", "--no-unsigned", dest="useUnsigned",
403 help="do not generate unsigned integer types",
404 action="store_false", default=True)
405
406 # Other builtins
407 group.add_option("", "--no-bool", dest="useBool",
408 help="do not generate bool types",
409 action="store_false", default=True)
410 group.add_option("", "--no-float", dest="useFloat",
411 help="do not generate float types",
412 action="store_false", default=True)
413 group.add_option("", "--no-double", dest="useDouble",
414 help="do not generate double types",
415 action="store_false", default=True)
416 group.add_option("", "--no-long-double", dest="useLongDouble",
417 help="do not generate long double types",
418 action="store_false", default=True)
419 group.add_option("", "--no-void-pointer", dest="useVoidPointer",
420 help="do not generate void* types",
421 action="store_false", default=True)
422
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000423 # Enumerations
424 group.add_option("", "--no-enums", dest="useEnum",
425 help="do not generate enum types",
426 action="store_false", default=True)
427
Daniel Dunbara83fb862009-01-15 04:24:17 +0000428 # Derived types
429 group.add_option("", "--no-array", dest="useArray",
430 help="do not generate record types",
431 action="store_false", default=True)
432 group.add_option("", "--no-complex", dest="useComplex",
433 help="do not generate complex types",
434 action="store_false", default=True)
435 group.add_option("", "--no-record", dest="useRecord",
436 help="do not generate record types",
437 action="store_false", default=True)
438 group.add_option("", "--no-union", dest="recordUseUnion",
439 help="do not generate union types",
440 action="store_false", default=True)
441 group.add_option("", "--no-vector", dest="useVector",
442 help="do not generate vector types",
443 action="store_false", default=True)
Daniel Dunbar122ed242009-05-07 23:19:55 +0000444 group.add_option("", "--no-bit-field", dest="useBitField",
445 help="do not generate bit-field record members",
446 action="store_false", default=True)
447 group.add_option("", "--no-builtins", dest="useBuiltins",
448 help="do not use any types",
449 action="store_false", default=True)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000450
451 # Tuning
452 group.add_option("", "--no-function-return", dest="functionUseReturn",
453 help="do not generate return types for functions",
454 action="store_false", default=True)
Daniel Dunbar0f1730d2009-02-22 04:17:53 +0000455 group.add_option("", "--vector-types", dest="vectorTypes",
456 help="comma separated list of vector types (e.g., v2i32) [default %default]",
Daniel Dunbarec1abb92009-03-02 06:14:33 +0000457 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 +0000458 group.add_option("", "--bit-fields", dest="bitFields",
459 help="comma separated list 'type:width' bit-field specifiers [default %default]",
Daniel Dunbar3d2fd8d2010-09-27 20:13:22 +0000460 action="store", type=str, default=(
461 "char:0,char:4,int:0,unsigned:1,int:1,int:4,int:13,int:24"))
Daniel Dunbara83fb862009-01-15 04:24:17 +0000462 group.add_option("", "--max-args", dest="functionMaxArgs",
463 help="maximum number of arguments per function [default %default]",
464 action="store", type=int, default=4, metavar="N")
465 group.add_option("", "--max-array", dest="arrayMaxSize",
466 help="maximum array size [default %default]",
467 action="store", type=int, default=4, metavar="N")
468 group.add_option("", "--max-record", dest="recordMaxSize",
469 help="maximum number of fields per record [default %default]",
470 action="store", type=int, default=4, metavar="N")
471 group.add_option("", "--max-record-depth", dest="recordMaxDepth",
472 help="maximum nested structure depth [default %default]",
473 action="store", type=int, default=None, metavar="N")
474 parser.add_option_group(group)
475 (opts, args) = parser.parse_args()
476
477 if not opts.useRandomSeed:
478 random.seed(opts.seed)
479
480 # Contruct type generator
481 builtins = []
Daniel Dunbar122ed242009-05-07 23:19:55 +0000482 if opts.useBuiltins:
483 ints = []
484 if opts.useChar: ints.append(('char',1))
485 if opts.useShort: ints.append(('short',2))
486 if opts.useInt: ints.append(('int',4))
487 # FIXME: Wrong size.
488 if opts.useLong: ints.append(('long',4))
489 if opts.useLongLong: ints.append(('long long',8))
490 if opts.useUnsigned:
491 ints = ([('unsigned %s'%i,s) for i,s in ints] +
492 [('signed %s'%i,s) for i,s in ints])
493 builtins.extend(ints)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000494
Daniel Dunbar122ed242009-05-07 23:19:55 +0000495 if opts.useBool: builtins.append(('_Bool',1))
496 if opts.useFloat: builtins.append(('float',4))
497 if opts.useDouble: builtins.append(('double',8))
498 if opts.useLongDouble: builtins.append(('long double',16))
499 # FIXME: Wrong size.
500 if opts.useVoidPointer: builtins.append(('void*',4))
Daniel Dunbara83fb862009-01-15 04:24:17 +0000501
Daniel Dunbar550faa32009-01-26 19:05:20 +0000502 btg = FixedTypeGenerator([BuiltinType(n,s) for n,s in builtins])
Daniel Dunbar122ed242009-05-07 23:19:55 +0000503
504 bitfields = []
505 for specifier in opts.bitFields.split(','):
506 if not specifier.strip():
507 continue
508 name,width = specifier.strip().split(':', 1)
509 bitfields.append(BuiltinType(name,None,int(width)))
510 bftg = FixedTypeGenerator(bitfields)
511
Daniel Dunbar0f1730d2009-02-22 04:17:53 +0000512 charType = BuiltinType('char',1)
513 shortType = BuiltinType('short',2)
514 intType = BuiltinType('int',4)
515 longlongType = BuiltinType('long long',8)
516 floatType = BuiltinType('float',4)
517 doubleType = BuiltinType('double',8)
518 sbtg = FixedTypeGenerator([charType, intType, floatType, doubleType])
Daniel Dunbara83fb862009-01-15 04:24:17 +0000519
520 atg = AnyTypeGenerator()
521 artg = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000522 def makeGenerator(atg, subgen, subfieldgen, useRecord, useArray, useBitField):
Daniel Dunbara83fb862009-01-15 04:24:17 +0000523 atg.addGenerator(btg)
Daniel Dunbar122ed242009-05-07 23:19:55 +0000524 if useBitField and opts.useBitField:
525 atg.addGenerator(bftg)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000526 if useRecord and opts.useRecord:
527 assert subgen
Daniel Dunbar122ed242009-05-07 23:19:55 +0000528 atg.addGenerator(RecordTypeGenerator(subfieldgen, opts.recordUseUnion,
Daniel Dunbara83fb862009-01-15 04:24:17 +0000529 opts.recordMaxSize))
530 if opts.useComplex:
531 # FIXME: Allow overriding builtins here
532 atg.addGenerator(ComplexTypeGenerator(sbtg))
533 if useArray and opts.useArray:
534 assert subgen
535 atg.addGenerator(ArrayTypeGenerator(subgen, opts.arrayMaxSize))
536 if opts.useVector:
Daniel Dunbar0f1730d2009-02-22 04:17:53 +0000537 vTypes = []
538 for i,t in enumerate(opts.vectorTypes.split(',')):
539 m = re.match('v([1-9][0-9]*)([if][1-9][0-9]*)', t.strip())
540 if not m:
541 parser.error('Invalid vector type: %r' % t)
542 count,kind = m.groups()
543 count = int(count)
544 type = { 'i8' : charType,
545 'i16' : shortType,
546 'i32' : intType,
547 'i64' : longlongType,
548 'f32' : floatType,
549 'f64' : doubleType,
550 }.get(kind)
551 if not type:
552 parser.error('Invalid vector type: %r' % t)
553 vTypes.append(ArrayType(i, True, type, count * type.size))
554
555 atg.addGenerator(FixedTypeGenerator(vTypes))
Douglas Gregoraa74a1e2010-02-02 20:10:50 +0000556 if opts.useEnum:
557 atg.addGenerator(EnumTypeGenerator([None, '-1', '1', '1u'], 1, 4))
Daniel Dunbara83fb862009-01-15 04:24:17 +0000558
559 if opts.recordMaxDepth is None:
560 # Fully recursive, just avoid top-level arrays.
Daniel Dunbar122ed242009-05-07 23:19:55 +0000561 subFTG = AnyTypeGenerator()
Daniel Dunbara83fb862009-01-15 04:24:17 +0000562 subTG = AnyTypeGenerator()
563 atg = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000564 makeGenerator(subFTG, atg, atg, True, True, True)
565 makeGenerator(subTG, atg, subFTG, True, True, False)
566 makeGenerator(atg, subTG, subFTG, True, False, False)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000567 else:
568 # Make a chain of type generators, each builds smaller
569 # structures.
570 base = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000571 fbase = AnyTypeGenerator()
572 makeGenerator(base, None, None, False, False, False)
573 makeGenerator(fbase, None, None, False, False, True)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000574 for i in range(opts.recordMaxDepth):
575 n = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000576 fn = AnyTypeGenerator()
577 makeGenerator(n, base, fbase, True, True, False)
578 makeGenerator(fn, base, fbase, True, True, True)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000579 base = n
Daniel Dunbar122ed242009-05-07 23:19:55 +0000580 fbase = fn
Daniel Dunbara83fb862009-01-15 04:24:17 +0000581 atg = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000582 makeGenerator(atg, base, fbase, True, False, False)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000583
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000584 if opts.testLayout:
585 ftg = atg
586 else:
587 ftg = FunctionTypeGenerator(atg, opts.functionUseReturn, opts.functionMaxArgs)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000588
589 # Override max,min,count if finite
590 if opts.maxIndex is None:
591 if ftg.cardinality is aleph0:
592 opts.maxIndex = 10000000
593 else:
594 opts.maxIndex = ftg.cardinality
595 opts.maxIndex = min(opts.maxIndex, ftg.cardinality)
596 opts.minIndex = max(0,min(opts.maxIndex-1, opts.minIndex))
597 if not opts.mode=='random':
598 opts.count = min(opts.count, opts.maxIndex-opts.minIndex)
599
600 if opts.output=='-':
601 output = sys.stdout
602 else:
603 output = open(opts.output,'w')
604 atexit.register(lambda: output.close())
605
606 outputHeader = None
607 if opts.outputHeader:
608 outputHeader = open(opts.outputHeader,'w')
609 atexit.register(lambda: outputHeader.close())
610
611 outputTests = None
612 if opts.outputTests:
613 outputTests = open(opts.outputTests,'w')
614 atexit.register(lambda: outputTests.close())
615
616 outputDriver = None
617 if opts.outputDriver:
618 outputDriver = open(opts.outputDriver,'w')
619 atexit.register(lambda: outputDriver.close())
620
621 info = ''
622 info += '// %s\n'%(' '.join(sys.argv),)
623 info += '// Generated: %s\n'%(time.strftime('%Y-%m-%d %H:%M'),)
624 info += '// Cardinality of function generator: %s\n'%(ftg.cardinality,)
625 info += '// Cardinality of type generator: %s\n'%(atg.cardinality,)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000626
627 if opts.testLayout:
628 info += '\n#include <stdio.h>'
Daniel Dunbara83fb862009-01-15 04:24:17 +0000629
630 P = TypePrinter(output,
631 outputHeader=outputHeader,
632 outputTests=outputTests,
633 outputDriver=outputDriver,
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000634 headerName=opts.outputHeader,
Daniel Dunbara83fb862009-01-15 04:24:17 +0000635 info=info)
636
637 def write(N):
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000638 try:
Daniel Dunbara83fb862009-01-15 04:24:17 +0000639 FT = ftg.get(N)
640 except RuntimeError,e:
641 if e.args[0]=='maximum recursion depth exceeded':
642 print >>sys.stderr,'WARNING: Skipped %d, recursion limit exceeded (bad arguments?)'%(N,)
643 return
644 raise
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000645 if opts.testLayout:
646 P.writeLayoutTest(N, FT)
647 else:
648 P.writeFunction(N, FT)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000649
650 if args:
651 [write(int(a)) for a in args]
652
Daniel Dunbar1ca717b2010-09-27 20:13:17 +0000653 skipTests = set(opts.skipTests)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000654 for i in range(opts.count):
655 if opts.mode=='linear':
656 index = opts.minIndex + i
657 else:
658 index = opts.minIndex + int((opts.maxIndex-opts.minIndex) * random.random())
Daniel Dunbar1ca717b2010-09-27 20:13:17 +0000659 if index in skipTests:
660 continue
Daniel Dunbara83fb862009-01-15 04:24:17 +0000661 write(index)
662
663 P.finish()
664
665if __name__=='__main__':
666 main()
667