blob: 63da02bcda9df5269f576b12a37bd6fe9fa8753f [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:
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) {'
Daniel Dunbar484c7ca2009-05-08 23:40:45 +000047 print >>self.outputDriver, ' int index = -1;'
48 print >>self.outputDriver, ' if (argc > 1) index = atoi(argv[1]);'
Daniel Dunbara83fb862009-01-15 04:24:17 +000049
50 def finish(self):
Daniel Dunbar5ce61572009-01-28 02:01:23 +000051 if self.layoutTests:
52 print >>self.output, 'int main(int argc, char **argv) {'
Daniel Dunbar484c7ca2009-05-08 23:40:45 +000053 print >>self.output, ' int index = -1;'
54 print >>self.output, ' if (argc > 1) index = atoi(argv[1]);'
55 for i,f in self.layoutTests:
56 print >>self.output, ' if (index == -1 || index == %d)' % i
57 print >>self.output, ' %s();' % f
Daniel Dunbar5ce61572009-01-28 02:01:23 +000058 print >>self.output, ' return 0;'
59 print >>self.output, '}'
60
Daniel Dunbara83fb862009-01-15 04:24:17 +000061 if self.outputDriver:
Daniel Dunbar9dd60b42009-02-17 23:13:43 +000062 print >>self.outputDriver, ' printf("DONE\\n");'
Daniel Dunbara83fb862009-01-15 04:24:17 +000063 print >>self.outputDriver, ' return 0;'
Daniel Dunbar5ce61572009-01-28 02:01:23 +000064 print >>self.outputDriver, '}'
Daniel Dunbara83fb862009-01-15 04:24:17 +000065
66 def getTypeName(self, T):
67 if isinstance(T,BuiltinType):
68 return T.name
69 name = self.types.get(T)
70 if name is None:
71 name = 'T%d'%(len(self.types),)
72 # Reserve slot
73 self.types[T] = None
74 if self.outputHeader:
75 print >>self.outputHeader,T.getTypedefDef(name, self)
76 else:
77 print >>self.output,T.getTypedefDef(name, self)
78 if self.outputTests:
79 print >>self.outputTests,T.getTypedefDef(name, self)
80 self.types[T] = name
81 return name
82
Daniel Dunbar5ce61572009-01-28 02:01:23 +000083 def writeLayoutTest(self, i, ty):
84 tyName = self.getTypeName(ty)
85 tyNameClean = tyName.replace(' ','_').replace('*','star')
86 fnName = 'test_%s' % tyNameClean
87
88 print >>self.output,'void %s(void) {' % fnName
89 self.printSizeOfType(' %s'%fnName, tyName, ty, self.output)
90 self.printAlignOfType(' %s'%fnName, tyName, ty, self.output)
91 self.printOffsetsOfType(' %s'%fnName, tyName, ty, self.output)
92 print >>self.output,'}'
93 print >>self.output
94
Daniel Dunbar484c7ca2009-05-08 23:40:45 +000095 self.layoutTests.append((i,fnName))
Daniel Dunbar5ce61572009-01-28 02:01:23 +000096
Daniel Dunbara83fb862009-01-15 04:24:17 +000097 def writeFunction(self, i, FT):
98 args = ', '.join(['%s arg%d'%(self.getTypeName(t),i) for i,t in enumerate(FT.argTypes)])
99 if not args:
100 args = 'void'
101
102 if FT.returnType is None:
103 retvalName = None
104 retvalTypeName = 'void'
105 else:
106 retvalTypeName = self.getTypeName(FT.returnType)
107 if self.writeBody or self.outputTests:
108 retvalName = self.getTestReturnValue(FT.returnType)
109
110 fnName = 'fn%d'%(FT.index,)
111 if self.outputHeader:
112 print >>self.outputHeader,'%s %s(%s);'%(retvalTypeName, fnName, args)
113 elif self.outputTests:
114 print >>self.outputTests,'%s %s(%s);'%(retvalTypeName, fnName, args)
115
116 print >>self.output,'%s %s(%s)'%(retvalTypeName, fnName, args),
117 if self.writeBody:
118 print >>self.output, '{'
119
120 for i,t in enumerate(FT.argTypes):
121 self.printValueOfType(' %s'%fnName, 'arg%d'%i, t)
122
123 if retvalName is not None:
124 print >>self.output, ' return %s;'%(retvalName,)
125 print >>self.output, '}'
126 else:
127 print >>self.output, '{}'
128 print >>self.output
129
130 if self.outputDriver:
Daniel Dunbar484c7ca2009-05-08 23:40:45 +0000131 print >>self.outputDriver, ' if (index == -1 || index == %d) {' % i
132 print >>self.outputDriver, ' extern void test_%s(void);' % fnName
133 print >>self.outputDriver, ' test_%s();' % fnName
134 print >>self.outputDriver, ' }'
Daniel Dunbara83fb862009-01-15 04:24:17 +0000135
136 if self.outputTests:
137 if self.outputHeader:
138 print >>self.outputHeader, 'void test_%s(void);'%(fnName,)
139
140 if retvalName is None:
141 retvalTests = None
142 else:
143 retvalTests = self.getTestValuesArray(FT.returnType)
144 tests = map(self.getTestValuesArray, FT.argTypes)
145 print >>self.outputTests, 'void test_%s(void) {'%(fnName,)
146
147 if retvalTests is not None:
148 print >>self.outputTests, ' printf("%s: testing return.\\n");'%(fnName,)
149 print >>self.outputTests, ' for (int i=0; i<%d; ++i) {'%(retvalTests[1],)
150 args = ', '.join(['%s[%d]'%(t,randrange(l)) for t,l in tests])
151 print >>self.outputTests, ' %s RV;'%(retvalTypeName,)
152 print >>self.outputTests, ' %s = %s[i];'%(retvalName, retvalTests[0])
153 print >>self.outputTests, ' RV = %s(%s);'%(fnName, args)
154 self.printValueOfType(' %s_RV'%fnName, 'RV', FT.returnType, output=self.outputTests, indent=4)
Daniel Dunbar9dd60b42009-02-17 23:13:43 +0000155 self.checkTypeValues('RV', '%s[i]' % retvalTests[0], FT.returnType, output=self.outputTests, indent=4)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000156 print >>self.outputTests, ' }'
157
158 if tests:
159 print >>self.outputTests, ' printf("%s: testing arguments.\\n");'%(fnName,)
160 for i,(array,length) in enumerate(tests):
161 for j in range(length):
162 args = ['%s[%d]'%(t,randrange(l)) for t,l in tests]
163 args[i] = '%s[%d]'%(array,j)
164 print >>self.outputTests, ' %s(%s);'%(fnName, ', '.join(args),)
165 print >>self.outputTests, '}'
166
167 def getTestReturnValue(self, type):
168 typeName = self.getTypeName(type)
169 info = self.testReturnValues.get(typeName)
170 if info is None:
171 name = '%s_retval'%(typeName.replace(' ','_').replace('*','star'),)
172 print >>self.output, '%s %s;'%(typeName,name)
173 if self.outputHeader:
174 print >>self.outputHeader, 'extern %s %s;'%(typeName,name)
175 elif self.outputTests:
176 print >>self.outputTests, 'extern %s %s;'%(typeName,name)
177 info = self.testReturnValues[typeName] = name
178 return info
179
180 def getTestValuesArray(self, type):
181 typeName = self.getTypeName(type)
182 info = self.testValues.get(typeName)
183 if info is None:
184 name = '%s_values'%(typeName.replace(' ','_').replace('*','star'),)
185 print >>self.outputTests, 'static %s %s[] = {'%(typeName,name)
186 length = 0
187 for item in self.getTestValues(type):
188 print >>self.outputTests, '\t%s,'%(item,)
189 length += 1
190 print >>self.outputTests,'};'
191 info = self.testValues[typeName] = (name,length)
192 return info
193
194 def getTestValues(self, t):
195 if isinstance(t, BuiltinType):
196 if t.name=='float':
197 for i in ['0.0','-1.0','1.0']:
198 yield i+'f'
199 elif t.name=='double':
200 for i in ['0.0','-1.0','1.0']:
201 yield i
202 elif t.name in ('void *'):
203 yield '(void*) 0'
204 yield '(void*) -1'
205 else:
206 yield '(%s) 0'%(t.name,)
207 yield '(%s) -1'%(t.name,)
208 yield '(%s) 1'%(t.name,)
209 elif isinstance(t, RecordType):
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000210 nonPadding = [f for f in t.fields
211 if not f.isPaddingBitField()]
212
213 if not nonPadding:
Daniel Dunbara83fb862009-01-15 04:24:17 +0000214 yield '{ }'
Daniel Dunbar900ed552009-01-29 07:36:46 +0000215 return
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000216
Daniel Dunbar900ed552009-01-29 07:36:46 +0000217 # FIXME: Use designated initializers to access non-first
218 # fields of unions.
219 if t.isUnion:
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000220 for v in self.getTestValues(nonPadding[0]):
221 yield '{ %s }' % v
Daniel Dunbar900ed552009-01-29 07:36:46 +0000222 return
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000223
224 fieldValues = map(list, map(self.getTestValues, nonPadding))
Daniel Dunbara83fb862009-01-15 04:24:17 +0000225 for i,values in enumerate(fieldValues):
226 for v in values:
227 elements = map(random.choice,fieldValues)
228 elements[i] = v
229 yield '{ %s }'%(', '.join(elements))
Daniel Dunbar48df17b2009-05-08 22:48:39 +0000230
Daniel Dunbara83fb862009-01-15 04:24:17 +0000231 elif isinstance(t, ComplexType):
232 for t in self.getTestValues(t.elementType):
Daniel Dunbar550faa32009-01-26 19:05:20 +0000233 yield '%s + %s * 1i'%(t,t)
234 elif isinstance(t, ArrayType):
Daniel Dunbara83fb862009-01-15 04:24:17 +0000235 values = list(self.getTestValues(t.elementType))
236 if not values:
237 yield '{ }'
Daniel Dunbar550faa32009-01-26 19:05:20 +0000238 for i in range(t.numElements):
Daniel Dunbara83fb862009-01-15 04:24:17 +0000239 for v in values:
Daniel Dunbar550faa32009-01-26 19:05:20 +0000240 elements = [random.choice(values) for i in range(t.numElements)]
Daniel Dunbara83fb862009-01-15 04:24:17 +0000241 elements[i] = v
242 yield '{ %s }'%(', '.join(elements))
243 else:
244 raise NotImplementedError,'Cannot make tests values of type: "%s"'%(t,)
245
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000246 def printSizeOfType(self, prefix, name, t, output=None, indent=2):
Eli Friedman98a71702009-05-25 21:38:01 +0000247 print >>output, '%*sprintf("%s: sizeof(%s) = %%ld\\n", (long)sizeof(%s));'%(indent, '', prefix, name, name)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000248 def printAlignOfType(self, prefix, name, t, output=None, indent=2):
Eli Friedman98a71702009-05-25 21:38:01 +0000249 print >>output, '%*sprintf("%s: __alignof__(%s) = %%ld\\n", (long)__alignof__(%s));'%(indent, '', prefix, name, name)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000250 def printOffsetsOfType(self, prefix, name, t, output=None, indent=2):
251 if isinstance(t, RecordType):
252 for i,f in enumerate(t.fields):
Eli Friedman98a71702009-05-25 21:38:01 +0000253 if f.isBitField():
Daniel Dunbar122ed242009-05-07 23:19:55 +0000254 continue
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000255 fname = 'field%d' % i
Eli Friedman98a71702009-05-25 21:38:01 +0000256 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 +0000257
Daniel Dunbara83fb862009-01-15 04:24:17 +0000258 def printValueOfType(self, prefix, name, t, output=None, indent=2):
259 if output is None:
260 output = self.output
261 if isinstance(t, BuiltinType):
262 if t.name.endswith('long long'):
263 code = 'lld'
264 elif t.name.endswith('long'):
265 code = 'ld'
266 elif t.name.split(' ')[-1] in ('_Bool','char','short','int'):
267 code = 'd'
268 elif t.name in ('float','double'):
269 code = 'f'
270 elif t.name == 'long double':
271 code = 'Lf'
272 else:
273 code = 'p'
274 print >>output, '%*sprintf("%s: %s = %%%s\\n", %s);'%(indent, '', prefix, name, code, name)
275 elif isinstance(t, RecordType):
276 if not t.fields:
277 print >>output, '%*sprintf("%s: %s (empty)\\n");'%(indent, '', prefix, name)
278 for i,f in enumerate(t.fields):
Daniel Dunbar122ed242009-05-07 23:19:55 +0000279 if f.isPaddingBitField():
280 continue
Daniel Dunbara83fb862009-01-15 04:24:17 +0000281 fname = '%s.field%d'%(name,i)
282 self.printValueOfType(prefix, fname, f, output=output, indent=indent)
283 elif isinstance(t, ComplexType):
284 self.printValueOfType(prefix, '(__real %s)'%name, t.elementType, output=output,indent=indent)
285 self.printValueOfType(prefix, '(__imag %s)'%name, t.elementType, output=output,indent=indent)
Daniel Dunbar550faa32009-01-26 19:05:20 +0000286 elif isinstance(t, ArrayType):
287 for i in range(t.numElements):
288 # Access in this fashion as a hackish way to portably
289 # access vectors.
Daniel Dunbare61e95f2009-01-29 08:48:06 +0000290 if t.isVector:
291 self.printValueOfType(prefix, '((%s*) &%s)[%d]'%(t.elementType,name,i), t.elementType, output=output,indent=indent)
292 else:
293 self.printValueOfType(prefix, '%s[%d]'%(name,i), t.elementType, output=output,indent=indent)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000294 else:
295 raise NotImplementedError,'Cannot print value of type: "%s"'%(t,)
296
Daniel Dunbar9dd60b42009-02-17 23:13:43 +0000297 def checkTypeValues(self, nameLHS, nameRHS, t, output=None, indent=2):
298 prefix = 'foo'
299 if output is None:
300 output = self.output
301 if isinstance(t, BuiltinType):
302 print >>output, '%*sassert(%s == %s);' % (indent, '', nameLHS, nameRHS)
303 elif isinstance(t, RecordType):
304 for i,f in enumerate(t.fields):
Daniel Dunbar122ed242009-05-07 23:19:55 +0000305 if f.isPaddingBitField():
306 continue
Daniel Dunbar9dd60b42009-02-17 23:13:43 +0000307 self.checkTypeValues('%s.field%d'%(nameLHS,i), '%s.field%d'%(nameRHS,i),
308 f, output=output, indent=indent)
309 if t.isUnion:
310 break
311 elif isinstance(t, ComplexType):
312 self.checkTypeValues('(__real %s)'%nameLHS, '(__real %s)'%nameRHS, t.elementType, output=output,indent=indent)
313 self.checkTypeValues('(__imag %s)'%nameLHS, '(__imag %s)'%nameRHS, t.elementType, output=output,indent=indent)
314 elif isinstance(t, ArrayType):
315 for i in range(t.numElements):
316 # Access in this fashion as a hackish way to portably
317 # access vectors.
318 if t.isVector:
319 self.checkTypeValues('((%s*) &%s)[%d]'%(t.elementType,nameLHS,i),
320 '((%s*) &%s)[%d]'%(t.elementType,nameRHS,i),
321 t.elementType, output=output,indent=indent)
322 else:
323 self.checkTypeValues('%s[%d]'%(nameLHS,i), '%s[%d]'%(nameRHS,i),
324 t.elementType, output=output,indent=indent)
325 else:
326 raise NotImplementedError,'Cannot print value of type: "%s"'%(t,)
327
Daniel Dunbara83fb862009-01-15 04:24:17 +0000328import sys
329
330def main():
331 from optparse import OptionParser, OptionGroup
332 parser = OptionParser("%prog [options] {indices}")
333 parser.add_option("", "--mode", dest="mode",
334 help="autogeneration mode (random or linear) [default %default]",
335 type='choice', choices=('random','linear'), default='linear')
336 parser.add_option("", "--count", dest="count",
337 help="autogenerate COUNT functions according to MODE",
338 type=int, default=0)
339 parser.add_option("", "--min", dest="minIndex", metavar="N",
340 help="start autogeneration with the Nth function type [default %default]",
341 type=int, default=0)
342 parser.add_option("", "--max", dest="maxIndex", metavar="N",
343 help="maximum index for random autogeneration [default %default]",
344 type=int, default=10000000)
345 parser.add_option("", "--seed", dest="seed",
346 help="random number generator seed [default %default]",
347 type=int, default=1)
348 parser.add_option("", "--use-random-seed", dest="useRandomSeed",
349 help="use random value for initial random number generator seed",
350 action='store_true', default=False)
351 parser.add_option("-o", "--output", dest="output", metavar="FILE",
352 help="write output to FILE [default %default]",
353 type=str, default='-')
354 parser.add_option("-O", "--output-header", dest="outputHeader", metavar="FILE",
355 help="write header file for output to FILE [default %default]",
356 type=str, default=None)
357 parser.add_option("-T", "--output-tests", dest="outputTests", metavar="FILE",
358 help="write function tests to FILE [default %default]",
359 type=str, default=None)
360 parser.add_option("-D", "--output-driver", dest="outputDriver", metavar="FILE",
361 help="write test driver to FILE [default %default]",
362 type=str, default=None)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000363 parser.add_option("", "--test-layout", dest="testLayout", metavar="FILE",
364 help="test structure layout",
365 action='store_true', default=False)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000366
367 group = OptionGroup(parser, "Type Enumeration Options")
368 # Builtins - Ints
369 group.add_option("", "--no-char", dest="useChar",
370 help="do not generate char types",
371 action="store_false", default=True)
372 group.add_option("", "--no-short", dest="useShort",
373 help="do not generate short types",
374 action="store_false", default=True)
375 group.add_option("", "--no-int", dest="useInt",
376 help="do not generate int types",
377 action="store_false", default=True)
378 group.add_option("", "--no-long", dest="useLong",
379 help="do not generate long types",
380 action="store_false", default=True)
381 group.add_option("", "--no-long-long", dest="useLongLong",
382 help="do not generate long long types",
383 action="store_false", default=True)
384 group.add_option("", "--no-unsigned", dest="useUnsigned",
385 help="do not generate unsigned integer types",
386 action="store_false", default=True)
387
388 # Other builtins
389 group.add_option("", "--no-bool", dest="useBool",
390 help="do not generate bool types",
391 action="store_false", default=True)
392 group.add_option("", "--no-float", dest="useFloat",
393 help="do not generate float types",
394 action="store_false", default=True)
395 group.add_option("", "--no-double", dest="useDouble",
396 help="do not generate double types",
397 action="store_false", default=True)
398 group.add_option("", "--no-long-double", dest="useLongDouble",
399 help="do not generate long double types",
400 action="store_false", default=True)
401 group.add_option("", "--no-void-pointer", dest="useVoidPointer",
402 help="do not generate void* types",
403 action="store_false", default=True)
404
405 # Derived types
406 group.add_option("", "--no-array", dest="useArray",
407 help="do not generate record types",
408 action="store_false", default=True)
409 group.add_option("", "--no-complex", dest="useComplex",
410 help="do not generate complex types",
411 action="store_false", default=True)
412 group.add_option("", "--no-record", dest="useRecord",
413 help="do not generate record types",
414 action="store_false", default=True)
415 group.add_option("", "--no-union", dest="recordUseUnion",
416 help="do not generate union types",
417 action="store_false", default=True)
418 group.add_option("", "--no-vector", dest="useVector",
419 help="do not generate vector types",
420 action="store_false", default=True)
Daniel Dunbar122ed242009-05-07 23:19:55 +0000421 group.add_option("", "--no-bit-field", dest="useBitField",
422 help="do not generate bit-field record members",
423 action="store_false", default=True)
424 group.add_option("", "--no-builtins", dest="useBuiltins",
425 help="do not use any types",
426 action="store_false", default=True)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000427
428 # Tuning
429 group.add_option("", "--no-function-return", dest="functionUseReturn",
430 help="do not generate return types for functions",
431 action="store_false", default=True)
Daniel Dunbar0f1730d2009-02-22 04:17:53 +0000432 group.add_option("", "--vector-types", dest="vectorTypes",
433 help="comma separated list of vector types (e.g., v2i32) [default %default]",
Daniel Dunbarec1abb92009-03-02 06:14:33 +0000434 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 +0000435 group.add_option("", "--bit-fields", dest="bitFields",
436 help="comma separated list 'type:width' bit-field specifiers [default %default]",
Daniel Dunbar238a3182009-05-08 20:10:52 +0000437 action="store", type=str, default="char:0,char:4,unsigned:0,unsigned:4,unsigned:13,unsigned:24")
Daniel Dunbara83fb862009-01-15 04:24:17 +0000438 group.add_option("", "--max-args", dest="functionMaxArgs",
439 help="maximum number of arguments per function [default %default]",
440 action="store", type=int, default=4, metavar="N")
441 group.add_option("", "--max-array", dest="arrayMaxSize",
442 help="maximum array size [default %default]",
443 action="store", type=int, default=4, metavar="N")
444 group.add_option("", "--max-record", dest="recordMaxSize",
445 help="maximum number of fields per record [default %default]",
446 action="store", type=int, default=4, metavar="N")
447 group.add_option("", "--max-record-depth", dest="recordMaxDepth",
448 help="maximum nested structure depth [default %default]",
449 action="store", type=int, default=None, metavar="N")
450 parser.add_option_group(group)
451 (opts, args) = parser.parse_args()
452
453 if not opts.useRandomSeed:
454 random.seed(opts.seed)
455
456 # Contruct type generator
457 builtins = []
Daniel Dunbar122ed242009-05-07 23:19:55 +0000458 if opts.useBuiltins:
459 ints = []
460 if opts.useChar: ints.append(('char',1))
461 if opts.useShort: ints.append(('short',2))
462 if opts.useInt: ints.append(('int',4))
463 # FIXME: Wrong size.
464 if opts.useLong: ints.append(('long',4))
465 if opts.useLongLong: ints.append(('long long',8))
466 if opts.useUnsigned:
467 ints = ([('unsigned %s'%i,s) for i,s in ints] +
468 [('signed %s'%i,s) for i,s in ints])
469 builtins.extend(ints)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000470
Daniel Dunbar122ed242009-05-07 23:19:55 +0000471 if opts.useBool: builtins.append(('_Bool',1))
472 if opts.useFloat: builtins.append(('float',4))
473 if opts.useDouble: builtins.append(('double',8))
474 if opts.useLongDouble: builtins.append(('long double',16))
475 # FIXME: Wrong size.
476 if opts.useVoidPointer: builtins.append(('void*',4))
Daniel Dunbara83fb862009-01-15 04:24:17 +0000477
Daniel Dunbar550faa32009-01-26 19:05:20 +0000478 btg = FixedTypeGenerator([BuiltinType(n,s) for n,s in builtins])
Daniel Dunbar122ed242009-05-07 23:19:55 +0000479
480 bitfields = []
481 for specifier in opts.bitFields.split(','):
482 if not specifier.strip():
483 continue
484 name,width = specifier.strip().split(':', 1)
485 bitfields.append(BuiltinType(name,None,int(width)))
486 bftg = FixedTypeGenerator(bitfields)
487
Daniel Dunbar0f1730d2009-02-22 04:17:53 +0000488 charType = BuiltinType('char',1)
489 shortType = BuiltinType('short',2)
490 intType = BuiltinType('int',4)
491 longlongType = BuiltinType('long long',8)
492 floatType = BuiltinType('float',4)
493 doubleType = BuiltinType('double',8)
494 sbtg = FixedTypeGenerator([charType, intType, floatType, doubleType])
Daniel Dunbara83fb862009-01-15 04:24:17 +0000495
496 atg = AnyTypeGenerator()
497 artg = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000498 def makeGenerator(atg, subgen, subfieldgen, useRecord, useArray, useBitField):
Daniel Dunbara83fb862009-01-15 04:24:17 +0000499 atg.addGenerator(btg)
Daniel Dunbar122ed242009-05-07 23:19:55 +0000500 if useBitField and opts.useBitField:
501 atg.addGenerator(bftg)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000502 if useRecord and opts.useRecord:
503 assert subgen
Daniel Dunbar122ed242009-05-07 23:19:55 +0000504 atg.addGenerator(RecordTypeGenerator(subfieldgen, opts.recordUseUnion,
Daniel Dunbara83fb862009-01-15 04:24:17 +0000505 opts.recordMaxSize))
506 if opts.useComplex:
507 # FIXME: Allow overriding builtins here
508 atg.addGenerator(ComplexTypeGenerator(sbtg))
509 if useArray and opts.useArray:
510 assert subgen
511 atg.addGenerator(ArrayTypeGenerator(subgen, opts.arrayMaxSize))
512 if opts.useVector:
Daniel Dunbar0f1730d2009-02-22 04:17:53 +0000513 vTypes = []
514 for i,t in enumerate(opts.vectorTypes.split(',')):
515 m = re.match('v([1-9][0-9]*)([if][1-9][0-9]*)', t.strip())
516 if not m:
517 parser.error('Invalid vector type: %r' % t)
518 count,kind = m.groups()
519 count = int(count)
520 type = { 'i8' : charType,
521 'i16' : shortType,
522 'i32' : intType,
523 'i64' : longlongType,
524 'f32' : floatType,
525 'f64' : doubleType,
526 }.get(kind)
527 if not type:
528 parser.error('Invalid vector type: %r' % t)
529 vTypes.append(ArrayType(i, True, type, count * type.size))
530
531 atg.addGenerator(FixedTypeGenerator(vTypes))
Daniel Dunbara83fb862009-01-15 04:24:17 +0000532
533 if opts.recordMaxDepth is None:
534 # Fully recursive, just avoid top-level arrays.
Daniel Dunbar122ed242009-05-07 23:19:55 +0000535 subFTG = AnyTypeGenerator()
Daniel Dunbara83fb862009-01-15 04:24:17 +0000536 subTG = AnyTypeGenerator()
537 atg = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000538 makeGenerator(subFTG, atg, atg, True, True, True)
539 makeGenerator(subTG, atg, subFTG, True, True, False)
540 makeGenerator(atg, subTG, subFTG, True, False, False)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000541 else:
542 # Make a chain of type generators, each builds smaller
543 # structures.
544 base = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000545 fbase = AnyTypeGenerator()
546 makeGenerator(base, None, None, False, False, False)
547 makeGenerator(fbase, None, None, False, False, True)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000548 for i in range(opts.recordMaxDepth):
549 n = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000550 fn = AnyTypeGenerator()
551 makeGenerator(n, base, fbase, True, True, False)
552 makeGenerator(fn, base, fbase, True, True, True)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000553 base = n
Daniel Dunbar122ed242009-05-07 23:19:55 +0000554 fbase = fn
Daniel Dunbara83fb862009-01-15 04:24:17 +0000555 atg = AnyTypeGenerator()
Daniel Dunbar122ed242009-05-07 23:19:55 +0000556 makeGenerator(atg, base, fbase, True, False, False)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000557
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000558 if opts.testLayout:
559 ftg = atg
560 else:
561 ftg = FunctionTypeGenerator(atg, opts.functionUseReturn, opts.functionMaxArgs)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000562
563 # Override max,min,count if finite
564 if opts.maxIndex is None:
565 if ftg.cardinality is aleph0:
566 opts.maxIndex = 10000000
567 else:
568 opts.maxIndex = ftg.cardinality
569 opts.maxIndex = min(opts.maxIndex, ftg.cardinality)
570 opts.minIndex = max(0,min(opts.maxIndex-1, opts.minIndex))
571 if not opts.mode=='random':
572 opts.count = min(opts.count, opts.maxIndex-opts.minIndex)
573
574 if opts.output=='-':
575 output = sys.stdout
576 else:
577 output = open(opts.output,'w')
578 atexit.register(lambda: output.close())
579
580 outputHeader = None
581 if opts.outputHeader:
582 outputHeader = open(opts.outputHeader,'w')
583 atexit.register(lambda: outputHeader.close())
584
585 outputTests = None
586 if opts.outputTests:
587 outputTests = open(opts.outputTests,'w')
588 atexit.register(lambda: outputTests.close())
589
590 outputDriver = None
591 if opts.outputDriver:
592 outputDriver = open(opts.outputDriver,'w')
593 atexit.register(lambda: outputDriver.close())
594
595 info = ''
596 info += '// %s\n'%(' '.join(sys.argv),)
597 info += '// Generated: %s\n'%(time.strftime('%Y-%m-%d %H:%M'),)
598 info += '// Cardinality of function generator: %s\n'%(ftg.cardinality,)
599 info += '// Cardinality of type generator: %s\n'%(atg.cardinality,)
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000600
601 if opts.testLayout:
602 info += '\n#include <stdio.h>'
Daniel Dunbara83fb862009-01-15 04:24:17 +0000603
604 P = TypePrinter(output,
605 outputHeader=outputHeader,
606 outputTests=outputTests,
607 outputDriver=outputDriver,
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000608 headerName=opts.outputHeader,
Daniel Dunbara83fb862009-01-15 04:24:17 +0000609 info=info)
610
611 def write(N):
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000612 try:
Daniel Dunbara83fb862009-01-15 04:24:17 +0000613 FT = ftg.get(N)
614 except RuntimeError,e:
615 if e.args[0]=='maximum recursion depth exceeded':
616 print >>sys.stderr,'WARNING: Skipped %d, recursion limit exceeded (bad arguments?)'%(N,)
617 return
618 raise
Daniel Dunbar5ce61572009-01-28 02:01:23 +0000619 if opts.testLayout:
620 P.writeLayoutTest(N, FT)
621 else:
622 P.writeFunction(N, FT)
Daniel Dunbara83fb862009-01-15 04:24:17 +0000623
624 if args:
625 [write(int(a)) for a in args]
626
627 for i in range(opts.count):
628 if opts.mode=='linear':
629 index = opts.minIndex + i
630 else:
631 index = opts.minIndex + int((opts.maxIndex-opts.minIndex) * random.random())
632 write(index)
633
634 P.finish()
635
636if __name__=='__main__':
637 main()
638