blob: a31f01043c35d439fe1d36909988f07d931f6c6a [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,)
210 elif isinstance(t, RecordType):
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000211 nonPadding = [f for f in t.fields
212 if not f.isPaddingBitField()]
213
214 if not nonPadding:
Daniel Dunbara83fb862009-01-15 04:24:17 +0000215 yield '{ }'
Daniel Dunbar900ed552009-01-29 07:36:46 +0000216 return
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000217
Daniel Dunbar900ed552009-01-29 07:36:46 +0000218 # FIXME: Use designated initializers to access non-first
219 # fields of unions.
220 if t.isUnion:
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000221 for v in self.getTestValues(nonPadding[0]):
222 yield '{ %s }' % v
Daniel Dunbar900ed552009-01-29 07:36:46 +0000223 return
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000224
225 fieldValues = map(list, map(self.getTestValues, nonPadding))
Daniel Dunbara83fb862009-01-15 04:24:17 +0000226 for i,values in enumerate(fieldValues):
227 for v in values:
228 elements = map(random.choice,fieldValues)
229 elements[i] = v
230 yield '{ %s }'%(', '.join(elements))
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000231
Daniel Dunbara83fb862009-01-15 04:24:17 +0000232 elif isinstance(t, ComplexType):
233 for t in self.getTestValues(t.elementType):
Daniel Dunbar550faa32009-01-26 19:05:20 +0000234 yield '%s + %s * 1i'%(t,t)
235 elif isinstance(t, ArrayType):
Daniel Dunbara83fb862009-01-15 04:24:17 +0000236 values = list(self.getTestValues(t.elementType))
237 if not values:
238 yield '{ }'
Daniel Dunbar550faa32009-01-26 19:05:20 +0000239 for i in range(t.numElements):
Daniel Dunbara83fb862009-01-15 04:24:17 +0000240 for v in values:
Daniel Dunbar550faa32009-01-26 19:05:20 +0000241 elements = [random.choice(values) for i in range(t.numElements)]
Daniel Dunbara83fb862009-01-15 04:24:17 +0000242 elements[i] = v
243 yield '{ %s }'%(', '.join(elements))
244 else:
245 raise NotImplementedError,'Cannot make tests values of type: "%s"'%(t,)
246
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000247 def printSizeOfType(self, prefix, name, t, output=None, indent=2):
Eli Friedman98a71702009-05-25 21:38:01 +0000248 print >>output, '%*sprintf("%s: sizeof(%s) = %%ld\\n", (long)sizeof(%s));'%(indent, '', prefix, name, name)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000249 def printAlignOfType(self, prefix, name, t, output=None, indent=2):
Eli Friedman98a71702009-05-25 21:38:01 +0000250 print >>output, '%*sprintf("%s: __alignof__(%s) = %%ld\\n", (long)__alignof__(%s));'%(indent, '', prefix, name, name)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000251 def printOffsetsOfType(self, prefix, name, t, output=None, indent=2):
252 if isinstance(t, RecordType):
253 for i,f in enumerate(t.fields):
Eli Friedman98a71702009-05-25 21:38:01 +0000254 if f.isBitField():
Daniel Dunbar122ed242009-05-07 23:19:55 +0000255 continue
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000256 fname = 'field%d' % i
Eli Friedman98a71702009-05-25 21:38:01 +0000257 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 +0000258
Daniel Dunbara83fb862009-01-15 04:24:17 +0000259 def printValueOfType(self, prefix, name, t, output=None, indent=2):
260 if output is None:
261 output = self.output
262 if isinstance(t, BuiltinType):
263 if t.name.endswith('long long'):
264 code = 'lld'
265 elif t.name.endswith('long'):
266 code = 'ld'
267 elif t.name.split(' ')[-1] in ('_Bool','char','short','int'):
268 code = 'd'
269 elif t.name in ('float','double'):
270 code = 'f'
271 elif t.name == 'long double':
272 code = 'Lf'
273 else:
274 code = 'p'
275 print >>output, '%*sprintf("%s: %s = %%%s\\n", %s);'%(indent, '', prefix, name, code, name)
276 elif isinstance(t, RecordType):
277 if not t.fields:
278 print >>output, '%*sprintf("%s: %s (empty)\\n");'%(indent, '', prefix, name)
279 for i,f in enumerate(t.fields):
Daniel Dunbar122ed242009-05-07 23:19:55 +0000280 if f.isPaddingBitField():
281 continue
Daniel Dunbara83fb862009-01-15 04:24:17 +0000282 fname = '%s.field%d'%(name,i)
283 self.printValueOfType(prefix, fname, f, output=output, indent=indent)
284 elif isinstance(t, ComplexType):
285 self.printValueOfType(prefix, '(__real %s)'%name, t.elementType, output=output,indent=indent)
286 self.printValueOfType(prefix, '(__imag %s)'%name, t.elementType, output=output,indent=indent)
Daniel Dunbar550faa32009-01-26 19:05:20 +0000287 elif isinstance(t, ArrayType):
288 for i in range(t.numElements):
289 # Access in this fashion as a hackish way to portably
290 # access vectors.
Daniel Dunbare61e95f2009-01-29 08:48:06 +0000291 if t.isVector:
292 self.printValueOfType(prefix, '((%s*) &%s)[%d]'%(t.elementType,name,i), t.elementType, output=output,indent=indent)
293 else:
294 self.printValueOfType(prefix, '%s[%d]'%(name,i), t.elementType, output=output,indent=indent)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000295 else:
296 raise NotImplementedError,'Cannot print value of type: "%s"'%(t,)
297
Daniel Dunbar9dd60b42009-02-17 23:13:43 +0000298 def checkTypeValues(self, nameLHS, nameRHS, t, output=None, indent=2):
299 prefix = 'foo'
300 if output is None:
301 output = self.output
302 if isinstance(t, BuiltinType):
303 print >>output, '%*sassert(%s == %s);' % (indent, '', nameLHS, nameRHS)
304 elif isinstance(t, RecordType):
305 for i,f in enumerate(t.fields):
Daniel Dunbar122ed242009-05-07 23:19:55 +0000306 if f.isPaddingBitField():
307 continue
Daniel Dunbar9dd60b42009-02-17 23:13:43 +0000308 self.checkTypeValues('%s.field%d'%(nameLHS,i), '%s.field%d'%(nameRHS,i),
309 f, output=output, indent=indent)
310 if t.isUnion:
311 break
312 elif isinstance(t, ComplexType):
313 self.checkTypeValues('(__real %s)'%nameLHS, '(__real %s)'%nameRHS, t.elementType, output=output,indent=indent)
314 self.checkTypeValues('(__imag %s)'%nameLHS, '(__imag %s)'%nameRHS, t.elementType, output=output,indent=indent)
315 elif isinstance(t, ArrayType):
316 for i in range(t.numElements):
317 # Access in this fashion as a hackish way to portably
318 # access vectors.
319 if t.isVector:
320 self.checkTypeValues('((%s*) &%s)[%d]'%(t.elementType,nameLHS,i),
321 '((%s*) &%s)[%d]'%(t.elementType,nameRHS,i),
322 t.elementType, output=output,indent=indent)
323 else:
324 self.checkTypeValues('%s[%d]'%(nameLHS,i), '%s[%d]'%(nameRHS,i),
325 t.elementType, output=output,indent=indent)
326 else:
327 raise NotImplementedError,'Cannot print value of type: "%s"'%(t,)
328
Daniel Dunbara83fb862009-01-15 04:24:17 +0000329import sys
330
331def main():
332 from optparse import OptionParser, OptionGroup
333 parser = OptionParser("%prog [options] {indices}")
334 parser.add_option("", "--mode", dest="mode",
335 help="autogeneration mode (random or linear) [default %default]",
336 type='choice', choices=('random','linear'), default='linear')
337 parser.add_option("", "--count", dest="count",
338 help="autogenerate COUNT functions according to MODE",
339 type=int, default=0)
340 parser.add_option("", "--min", dest="minIndex", metavar="N",
341 help="start autogeneration with the Nth function type [default %default]",
342 type=int, default=0)
343 parser.add_option("", "--max", dest="maxIndex", metavar="N",
344 help="maximum index for random autogeneration [default %default]",
345 type=int, default=10000000)
346 parser.add_option("", "--seed", dest="seed",
347 help="random number generator seed [default %default]",
348 type=int, default=1)
349 parser.add_option("", "--use-random-seed", dest="useRandomSeed",
350 help="use random value for initial random number generator seed",
351 action='store_true', default=False)
352 parser.add_option("-o", "--output", dest="output", metavar="FILE",
353 help="write output to FILE [default %default]",
354 type=str, default='-')
355 parser.add_option("-O", "--output-header", dest="outputHeader", metavar="FILE",
356 help="write header file for output to FILE [default %default]",
357 type=str, default=None)
358 parser.add_option("-T", "--output-tests", dest="outputTests", metavar="FILE",
359 help="write function tests to FILE [default %default]",
360 type=str, default=None)
361 parser.add_option("-D", "--output-driver", dest="outputDriver", metavar="FILE",
362 help="write test driver to FILE [default %default]",
363 type=str, default=None)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000364 parser.add_option("", "--test-layout", dest="testLayout", metavar="FILE",
365 help="test structure layout",
366 action='store_true', default=False)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000367
368 group = OptionGroup(parser, "Type Enumeration Options")
369 # Builtins - Ints
370 group.add_option("", "--no-char", dest="useChar",
371 help="do not generate char types",
372 action="store_false", default=True)
373 group.add_option("", "--no-short", dest="useShort",
374 help="do not generate short types",
375 action="store_false", default=True)
376 group.add_option("", "--no-int", dest="useInt",
377 help="do not generate int types",
378 action="store_false", default=True)
379 group.add_option("", "--no-long", dest="useLong",
380 help="do not generate long types",
381 action="store_false", default=True)
382 group.add_option("", "--no-long-long", dest="useLongLong",
383 help="do not generate long long types",
384 action="store_false", default=True)
385 group.add_option("", "--no-unsigned", dest="useUnsigned",
386 help="do not generate unsigned integer types",
387 action="store_false", default=True)
388
389 # Other builtins
390 group.add_option("", "--no-bool", dest="useBool",
391 help="do not generate bool types",
392 action="store_false", default=True)
393 group.add_option("", "--no-float", dest="useFloat",
394 help="do not generate float types",
395 action="store_false", default=True)
396 group.add_option("", "--no-double", dest="useDouble",
397 help="do not generate double types",
398 action="store_false", default=True)
399 group.add_option("", "--no-long-double", dest="useLongDouble",
400 help="do not generate long double types",
401 action="store_false", default=True)
402 group.add_option("", "--no-void-pointer", dest="useVoidPointer",
403 help="do not generate void* types",
404 action="store_false", default=True)
405
406 # Derived types
407 group.add_option("", "--no-array", dest="useArray",
408 help="do not generate record types",
409 action="store_false", default=True)
410 group.add_option("", "--no-complex", dest="useComplex",
411 help="do not generate complex types",
412 action="store_false", default=True)
413 group.add_option("", "--no-record", dest="useRecord",
414 help="do not generate record types",
415 action="store_false", default=True)
416 group.add_option("", "--no-union", dest="recordUseUnion",
417 help="do not generate union types",
418 action="store_false", default=True)
419 group.add_option("", "--no-vector", dest="useVector",
420 help="do not generate vector types",
421 action="store_false", default=True)
Daniel Dunbar122ed242009-05-07 23:19:55 +0000422 group.add_option("", "--no-bit-field", dest="useBitField",
423 help="do not generate bit-field record members",
424 action="store_false", default=True)
425 group.add_option("", "--no-builtins", dest="useBuiltins",
426 help="do not use any types",
427 action="store_false", default=True)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000428
429 # Tuning
430 group.add_option("", "--no-function-return", dest="functionUseReturn",
431 help="do not generate return types for functions",
432 action="store_false", default=True)
Daniel Dunbar0f1730d2009-02-22 04:17:53 +0000433 group.add_option("", "--vector-types", dest="vectorTypes",
434 help="comma separated list of vector types (e.g., v2i32) [default %default]",
Daniel Dunbarec1abb92009-03-02 06:14:33 +0000435 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 +0000436 group.add_option("", "--bit-fields", dest="bitFields",
437 help="comma separated list 'type:width' bit-field specifiers [default %default]",
Daniel Dunbar238a3182009-05-08 20:10:52 +0000438 action="store", type=str, default="char:0,char:4,unsigned:0,unsigned:4,unsigned:13,unsigned:24")
Daniel Dunbara83fb862009-01-15 04:24:17 +0000439 group.add_option("", "--max-args", dest="functionMaxArgs",
440 help="maximum number of arguments per function [default %default]",
441 action="store", type=int, default=4, metavar="N")
442 group.add_option("", "--max-array", dest="arrayMaxSize",
443 help="maximum array size [default %default]",
444 action="store", type=int, default=4, metavar="N")
445 group.add_option("", "--max-record", dest="recordMaxSize",
446 help="maximum number of fields per record [default %default]",
447 action="store", type=int, default=4, metavar="N")
448 group.add_option("", "--max-record-depth", dest="recordMaxDepth",
449 help="maximum nested structure depth [default %default]",
450 action="store", type=int, default=None, metavar="N")
451 parser.add_option_group(group)
452 (opts, args) = parser.parse_args()
453
454 if not opts.useRandomSeed:
455 random.seed(opts.seed)
456
457 # Contruct type generator
458 builtins = []
Daniel Dunbar122ed242009-05-07 23:19:55 +0000459 if opts.useBuiltins:
460 ints = []
461 if opts.useChar: ints.append(('char',1))
462 if opts.useShort: ints.append(('short',2))
463 if opts.useInt: ints.append(('int',4))
464 # FIXME: Wrong size.
465 if opts.useLong: ints.append(('long',4))
466 if opts.useLongLong: ints.append(('long long',8))
467 if opts.useUnsigned:
468 ints = ([('unsigned %s'%i,s) for i,s in ints] +
469 [('signed %s'%i,s) for i,s in ints])
470 builtins.extend(ints)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000471
Daniel Dunbar122ed242009-05-07 23:19:55 +0000472 if opts.useBool: builtins.append(('_Bool',1))
473 if opts.useFloat: builtins.append(('float',4))
474 if opts.useDouble: builtins.append(('double',8))
475 if opts.useLongDouble: builtins.append(('long double',16))
476 # FIXME: Wrong size.
477 if opts.useVoidPointer: builtins.append(('void*',4))
Daniel Dunbara83fb862009-01-15 04:24:17 +0000478
Daniel Dunbar550faa32009-01-26 19:05:20 +0000479 btg = FixedTypeGenerator([BuiltinType(n,s) for n,s in builtins])
Daniel Dunbar122ed242009-05-07 23:19:55 +0000480
481 bitfields = []
482 for specifier in opts.bitFields.split(','):
483 if not specifier.strip():
484 continue
485 name,width = specifier.strip().split(':', 1)
486 bitfields.append(BuiltinType(name,None,int(width)))
487 bftg = FixedTypeGenerator(bitfields)
488
Daniel Dunbar0f1730d2009-02-22 04:17:53 +0000489 charType = BuiltinType('char',1)
490 shortType = BuiltinType('short',2)
491 intType = BuiltinType('int',4)
492 longlongType = BuiltinType('long long',8)
493 floatType = BuiltinType('float',4)
494 doubleType = BuiltinType('double',8)
495 sbtg = FixedTypeGenerator([charType, intType, floatType, doubleType])
Daniel Dunbara83fb862009-01-15 04:24:17 +0000496
497 atg = AnyTypeGenerator()
498 artg = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000499 def makeGenerator(atg, subgen, subfieldgen, useRecord, useArray, useBitField):
Daniel Dunbara83fb862009-01-15 04:24:17 +0000500 atg.addGenerator(btg)
Daniel Dunbar122ed242009-05-07 23:19:55 +0000501 if useBitField and opts.useBitField:
502 atg.addGenerator(bftg)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000503 if useRecord and opts.useRecord:
504 assert subgen
Daniel Dunbar122ed242009-05-07 23:19:55 +0000505 atg.addGenerator(RecordTypeGenerator(subfieldgen, opts.recordUseUnion,
Daniel Dunbara83fb862009-01-15 04:24:17 +0000506 opts.recordMaxSize))
507 if opts.useComplex:
508 # FIXME: Allow overriding builtins here
509 atg.addGenerator(ComplexTypeGenerator(sbtg))
510 if useArray and opts.useArray:
511 assert subgen
512 atg.addGenerator(ArrayTypeGenerator(subgen, opts.arrayMaxSize))
513 if opts.useVector:
Daniel Dunbar0f1730d2009-02-22 04:17:53 +0000514 vTypes = []
515 for i,t in enumerate(opts.vectorTypes.split(',')):
516 m = re.match('v([1-9][0-9]*)([if][1-9][0-9]*)', t.strip())
517 if not m:
518 parser.error('Invalid vector type: %r' % t)
519 count,kind = m.groups()
520 count = int(count)
521 type = { 'i8' : charType,
522 'i16' : shortType,
523 'i32' : intType,
524 'i64' : longlongType,
525 'f32' : floatType,
526 'f64' : doubleType,
527 }.get(kind)
528 if not type:
529 parser.error('Invalid vector type: %r' % t)
530 vTypes.append(ArrayType(i, True, type, count * type.size))
531
532 atg.addGenerator(FixedTypeGenerator(vTypes))
Daniel Dunbara83fb862009-01-15 04:24:17 +0000533
534 if opts.recordMaxDepth is None:
535 # Fully recursive, just avoid top-level arrays.
Daniel Dunbar122ed242009-05-07 23:19:55 +0000536 subFTG = AnyTypeGenerator()
Daniel Dunbara83fb862009-01-15 04:24:17 +0000537 subTG = AnyTypeGenerator()
538 atg = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000539 makeGenerator(subFTG, atg, atg, True, True, True)
540 makeGenerator(subTG, atg, subFTG, True, True, False)
541 makeGenerator(atg, subTG, subFTG, True, False, False)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000542 else:
543 # Make a chain of type generators, each builds smaller
544 # structures.
545 base = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000546 fbase = AnyTypeGenerator()
547 makeGenerator(base, None, None, False, False, False)
548 makeGenerator(fbase, None, None, False, False, True)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000549 for i in range(opts.recordMaxDepth):
550 n = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000551 fn = AnyTypeGenerator()
552 makeGenerator(n, base, fbase, True, True, False)
553 makeGenerator(fn, base, fbase, True, True, True)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000554 base = n
Daniel Dunbar122ed242009-05-07 23:19:55 +0000555 fbase = fn
Daniel Dunbara83fb862009-01-15 04:24:17 +0000556 atg = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000557 makeGenerator(atg, base, fbase, True, False, False)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000558
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000559 if opts.testLayout:
560 ftg = atg
561 else:
562 ftg = FunctionTypeGenerator(atg, opts.functionUseReturn, opts.functionMaxArgs)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000563
564 # Override max,min,count if finite
565 if opts.maxIndex is None:
566 if ftg.cardinality is aleph0:
567 opts.maxIndex = 10000000
568 else:
569 opts.maxIndex = ftg.cardinality
570 opts.maxIndex = min(opts.maxIndex, ftg.cardinality)
571 opts.minIndex = max(0,min(opts.maxIndex-1, opts.minIndex))
572 if not opts.mode=='random':
573 opts.count = min(opts.count, opts.maxIndex-opts.minIndex)
574
575 if opts.output=='-':
576 output = sys.stdout
577 else:
578 output = open(opts.output,'w')
579 atexit.register(lambda: output.close())
580
581 outputHeader = None
582 if opts.outputHeader:
583 outputHeader = open(opts.outputHeader,'w')
584 atexit.register(lambda: outputHeader.close())
585
586 outputTests = None
587 if opts.outputTests:
588 outputTests = open(opts.outputTests,'w')
589 atexit.register(lambda: outputTests.close())
590
591 outputDriver = None
592 if opts.outputDriver:
593 outputDriver = open(opts.outputDriver,'w')
594 atexit.register(lambda: outputDriver.close())
595
596 info = ''
597 info += '// %s\n'%(' '.join(sys.argv),)
598 info += '// Generated: %s\n'%(time.strftime('%Y-%m-%d %H:%M'),)
599 info += '// Cardinality of function generator: %s\n'%(ftg.cardinality,)
600 info += '// Cardinality of type generator: %s\n'%(atg.cardinality,)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000601
602 if opts.testLayout:
603 info += '\n#include <stdio.h>'
Daniel Dunbara83fb862009-01-15 04:24:17 +0000604
605 P = TypePrinter(output,
606 outputHeader=outputHeader,
607 outputTests=outputTests,
608 outputDriver=outputDriver,
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000609 headerName=opts.outputHeader,
Daniel Dunbara83fb862009-01-15 04:24:17 +0000610 info=info)
611
612 def write(N):
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000613 try:
Daniel Dunbara83fb862009-01-15 04:24:17 +0000614 FT = ftg.get(N)
615 except RuntimeError,e:
616 if e.args[0]=='maximum recursion depth exceeded':
617 print >>sys.stderr,'WARNING: Skipped %d, recursion limit exceeded (bad arguments?)'%(N,)
618 return
619 raise
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000620 if opts.testLayout:
621 P.writeLayoutTest(N, FT)
622 else:
623 P.writeFunction(N, FT)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000624
625 if args:
626 [write(int(a)) for a in args]
627
628 for i in range(opts.count):
629 if opts.mode=='linear':
630 index = opts.minIndex + i
631 else:
632 index = opts.minIndex + int((opts.maxIndex-opts.minIndex) * random.random())
633 write(index)
634
635 P.finish()
636
637if __name__=='__main__':
638 main()
639